﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Forms;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Geometry;
using System.Data.SQLite;
using System.Data;
using System.Data.Common;
//using Autodesk.AutoCAD.GraphicsInterface;
using Autodesk.AutoCAD.PlottingServices;
//using Autodesk.AutoCAD.PlottingServices;
//using Application = Autodesk.AutoCAD.ApplicationServices.Core.Application;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using System.Threading;
using System.ComponentModel;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using PdfiumViewer;


namespace cadbom
{

    public class home
    {
        private PdfProgressForm pdfform;
        private LoginForm loginForm;
        private SqlLiteUtils sqlLite;
        private BomForm bomForm;
        private BindingList<BasProcess> basProcessList;
        private SetProcessName setProcessNameForm;
        private List<String> itemList;
        ResultBuffer rbXdata;
        long handleId;
        private string domain;
        private string selectedProductCode = "";
        private string selectedProcessName = "";
        OutMsg outMsg = new OutMsg();
        CommandForm commandForm = null;
        HongShengFeiForm hongShengFeiForm = null;
        BaiGeForm baigeForm = null;
        FuYuanForm fuYuanForm = null;
        SetObject setObjectTTE = null;
        SetBomMaterialForm setBomMaterialForm = null;
        NetApi netApi = new NetApi();

        SelectPDFTypeForm pdfTypeForm = null;

        [DllImport("accore.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedTrans")]

        static extern int acedTrans(double[] point, IntPtr fromRb, IntPtr toRb, int disp, double[] result);
        public home()
        {
           log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.config"));           
        }
        #region 操作命令代码块
        [CommandMethod("TT3")]
        public void ShowLoginCommand()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor editor = doc.Editor;
            if (loginForm == null)
            {
                // 创建 Windows Form 窗口
                loginForm = new LoginForm();
                loginForm.FormClosed += LoginForm_FormClosed;
            }
            InitDomainConfig();
            GetDomainTenant();
            // 显示 Windows Form 窗口
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, loginForm);
        }

        [CommandMethod("WindowCommand")]
        public void WindowCommand()
        {
            if (commandForm == null)
            {
                commandForm = new CommandForm();   
            }
            // 显示 Windows Form 窗口
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, commandForm);
        }

        //[CommandMethod("TT6")]
        //public void CreateDb()
        //{
        //    SqlLiteUtils sq = new SqlLiteUtils();
        //    sq.createDb();
        //}

        [CommandMethod("TT1")]
        [STAThreadAttribute]
        public void ShowBomCommand()
        {
            if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
            {
                Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
            }
            try
            {
                InitDomainConfig(); //2025425百舸项目调整读取创建productcode
                getUserInfo();
                LogHelper.WriteLog("开始创建表格！");
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Editor editor = doc.Editor;
                GValues.clickButtonText = "插入";
                if (bomForm == null)
                {
                    try
                    {
                        //var thread = new Thread(() =>
                        //{

                        //});
                        //thread.SetApartmentState(ApartmentState.STA);  // 明确线程模型
                        //thread.Start();
                        // 创建 Windows Form 窗口
                        bomForm = new BomForm();
                        bomForm.FormClosed += BomForm_FormClosed;

                    }
                    catch (System.InvalidOperationException e)
                    {
                        MessageBox.Show(e.Message);
                    }
                    catch (System.Threading.ThreadStateException e)
                    {
                        MessageBox.Show(e.Message);
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                    //bomForm.Disposed += BomForm_Disposed;
                }
                else
                {
                    try
                    {
                        bomForm.Close();
                        bomForm.Dispose();
                        bomForm = null;
                        //var thread = new Thread(() =>
                        //{

                        //});
                        //thread.SetApartmentState(ApartmentState.STA);  // 明确线程模型
                        //thread.Start();
                        // 创建 Windows Form 窗口
                        bomForm = new BomForm();
                        bomForm.FormClosed += BomForm_FormClosed;

                    }
                    catch (System.InvalidOperationException e)
                    {
                        MessageBox.Show(e.Message);
                    }
                    catch (System.Threading.ThreadStateException e)
                    {
                        MessageBox.Show(e.Message);
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
                //bomForm.WindowState = FormWindowState.Normal;
                InitTableEvent();
                //InitDomainConfig();
                //getUserInfo();
                if (GValues.CADCreateProductCode)
                {
                    bomForm.BaigeBlockGetProductCode(new Action<string>(r =>
                    {
                        bomForm.BaigeSetInputProduct(GValues.productCode);
                        //MessageBox.Show(" return : " + r);
                        Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, bomForm);
                        bomForm.initBomFromData();
                    }));
                }
                else
                {
                    GValues.productCode = "";
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, bomForm);
                    bomForm.initBomFromData();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void BaigeInsertTable()
        {
            MessageBox.Show(" insert table....");
            LogHelper.WriteLog("开始创建表格！");
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor editor = doc.Editor;
            GValues.clickButtonText = "插入";           
            if (bomForm == null)
            {
                // 创建 Windows Form 窗口
                bomForm = new BomForm();
                bomForm.FormClosed += BomForm_FormClosed;
                //bomForm.Disposed += BomForm_Disposed;
            }
            //bomForm.WindowState = FormWindowState.Normal;
            InitTableEvent();
            //InitDomainConfig();
            //getUserInfo();

            // 显示 Windows Form 窗口
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, bomForm);
            bomForm.initBomFromData();
        }
       
        //复制升版料号
        [CommandMethod("TT4")]
        public void CopyBomCommand()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            string productCode = "";
            string domainid = "";
            GValues.clickButtonText = "复制";
            PromptSelectionOptions options = new PromptSelectionOptions();
            options.MessageForAdding = "选择表格对象";
            PromptSelectionResult result = ed.GetSelection(options);


            if (result.Status == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    SelectionSet ss = result.Value;
                    foreach (ObjectId id in ss.GetObjectIds())
                    {
                        Entity entity = tr.GetObject(id, OpenMode.ForRead) as Entity;
                        if (entity is Table)
                        {
                            Table table = entity as Table;

                            // 你现在可以使用table对象了
                            // ...
                            if (table.XData != null)
                            {
                                ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                // 遍历ResultBuffer以查看数据
                                foreach (TypedValue tv in rb)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            domainid = tv.Value.ToString();
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            productCode = tv.Value.ToString();
                                            break;
                                        // 其他类型的DXF组码...
                                    }
                                }
                            }
                            else
                            {
                                ed.WriteMessage("\n实体没有扩展数据！");
                            }
                        }
                    }
                    tr.Commit();
                }
            }
            if (productCode != "")
            {
                GValues.productCode = productCode;
                this.ModifyBomCommand();

            }

        }
        //[CommandMethod("simprev")]
        //static public void SimplePreview()
        //{
        //    Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        //    Editor ed = doc.Editor;
        //    Database db = doc.Database;
        //    // PlotEngines do the previewing and plotting
        //    if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
        //    {
        //        // First we preview...
        //        PreviewEndPlotStatus stat;
        //        PlotEngine pre = PlotFactory.CreatePreviewEngine((int)PreviewEngineFlags.Plot);

        //        using (pre)
        //        {
        //            stat = PreviewCommands.PlotOrPreview(pre, true, db.CurrentSpaceId, "");
        //        }
        //        if (stat == PreviewEndPlotStatus.Plot)
        //        {
        //            // And if the user asks, we plot...
        //            PlotEngine ple = PlotFactory.CreatePublishEngine();
        //            stat = PreviewCommands.PlotOrPreview(ple, false, db.CurrentSpaceId, "c:\\previewed-plot");
        //        }
        //    }
        //    else
        //    {
        //        ed.WriteMessage("\nAnother plot is in progress.");
        //    }
        //}
        [CommandMethod("InsertTableCorrected")]
        public void InsertTableCorrected()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            //// 获取当前UCS
            //CoordinateSystem3d ucs =(CoordinateSystem3d) ed.CurrentUserCoordinateSystem;

            // 获取点击点并转换
            PromptPointResult ppr = ed.GetPoint("\n选择插入点: ");
            if (ppr.Status != PromptStatus.OK) return;

            // 确保使用世界坐标
            Point3d worldPoint = ConvertToWorldCoordinate(ppr.Value,ed);

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 创建表格
                Table table = new Table();
                table.Position = worldPoint;

                // 其他表格设置...

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(
                    db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(table);
                tr.AddNewlyCreatedDBObject(table, true);

                tr.Commit();
            }
        }
        private Point3d ConvertToWorldCoordinate(Point3d point, Editor ed)
        {
            // 正确的方法：使用Matrix3d进行坐标转换
            Matrix3d ucsToWcs = ed.CurrentUserCoordinateSystem;
            return point.TransformBy(ucsToWcs);
        }

        [CommandMethod("CheckHandelId")]
        public void QueryTableId()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            string productCode = "";
            string domainid = "";
            GValues.clickButtonText = "修改";
            PromptSelectionOptions options = new PromptSelectionOptions();
            options.MessageForAdding = "选择表格对象";
            PromptSelectionResult result = ed.GetSelection(options);


            if (result.Status == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    SelectionSet ss = result.Value;
                    foreach (ObjectId id in ss.GetObjectIds())
                    {
                        Entity entity = tr.GetObject(id, OpenMode.ForRead) as Entity;
                        if (entity is Table)
                        {
                            Table table = entity as Table;

                            // 你现在可以使用table对象了
                            // ...
                            ed.WriteMessage("handel id:" + table.Handle.Value);
                        }
                    }
                    tr.Commit();
                }
            }
            if (productCode != "")
            {
                GValues.productCode = productCode;
                this.ModifyBomCommand();

            }
        }
        #region 打印pdf测试代码


        //public Point3d WcsToUcs(Point3d wcsPoint)
        //{
        //    Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        //    Database db = doc.Database;
        //    Transaction tr = db.TransactionManager.StartTransaction();

        //    using (tr)
        //    {
        //        // 获取当前UCS
        //        Matrix3d ucsMatrix = db.Ucsmatrix;

        //        // 将WCS点转换到UCS
        //        Point3d ucsPoint = ucsMatrix.ConvertPointToUcs(wcsPoint);

        //        return ucsPoint;
        //    }
        //}


//public class CoordinateConverter
//{
//    public Point3d ConvertWCSToUCS(Point3d wcsPoint)
//    {
//        Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
//        Database db = doc.Database;
//        Editor ed = doc.Editor;

//        using (Transaction trans = db.TransactionManager.StartTransaction())
//        {
//            BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
//            BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

//            // 获取当前UCS
//            Matrix3d ucs = ed.CurrentUserCoordinateSystem;

//            // 将WCS坐标转换为UCS坐标
//            Matrix3d wcsToUCS = Matrix3d.PlaneToWorld(ucs.CoordinateSystem3d);
//            Point3d ucsPoint = wcsPoint.TransformBy(wcsToUCS);

//            trans.Commit();

//            return ucsPoint;
//        }
//    }
//}
        //[CommandMethod("WW77")]
        //public void sendFile()
        //{
        //    Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        //    Editor ed = doc.Editor;
        //    String OutPath = GValues.pdfPath + "\\selectDWGWindow.pdf";
        //    // 判断文件是否存在
        //    if (File.Exists(OutPath))
        //    {
        //        uploadPdf();
        //        ed.WriteMessage("上传成功！");
        //    }
        //    else
        //    {
        //        ed.WriteMessage("文件不存在！");
        //    }

        //}

        [CommandMethod("TT61")]
        public void KeerdaGlobalPlotToPdf()
        {
            InitDomainConfig();
            KeerdaGetProductCode();
        }

        [CommandMethod("TT62")]
        public void KeerdaGlobalPlotToPNG()
        {
            InitDomainConfig();
            KeerdaGetProductCodePNG();
        }
        [CommandMethod("TT6")]
        public void GlobalPlotToPdf()
        {
            InitDomainConfig();
            if (GValues.CADCreateProductDwgFile)
            {
                BaigeCopyToNewDwg();
            }
            else
            {
                PlotBlockColToPDF();
            }
        }
        public void BaigeCopyToNewDwg(){
            if (pdfTypeForm == null || pdfTypeForm.IsDisposed)
            {
                pdfTypeForm = new SelectPDFTypeForm();
                pdfTypeForm.initData(new Action<int>(r => {
                    _BaigeCopyToNewDwg(r);
                }));
            }
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, pdfTypeForm);

        }
        public void _BaigeCopyToNewDwg(int type)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            //
                //var helper = new LayerXDataHelper();
                //ResultBuffer xdata = helper.GetLayerXData("0", "ACAD");

                //if (xdata != null)
                //{
                //    foreach (TypedValue tv in xdata)
                //    {
                //        if (tv.TypeCode == (int)DxfCode.Text)
                //        {
                //            ed.WriteMessage("图层XData: {tv.Value}" + tv.Value);
                //        }
                //    }
                //}

            //



            string filename = "code";
            string productName = "";
            try
            {
                PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                ppo.AllowNone = false;
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d pt1 = ppr.Value;
                PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", pt1);
                ppr = ed.GetCorner(pco);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d pt2 = ppr.Value;


                // 1. 用户输入对角点，创建选择窗口
                //PromptPointResult ppr1 = ed.GetPoint("\n请输入第一个对角点: ");
                //if (ppr1.Status != PromptStatus.OK) return;

                //PromptPointOptions ppo2 = new PromptPointOptions("\n请输入第二个对角点: ");
                //ppo2.BasePoint = ppr1.Value;
                //ppo2.UseBasePoint = true;
                //PromptPointResult ppr2 = ed.GetCorner(ppo2);
                //if (ppr2.Status != PromptStatus.OK) return;

                //Point3d pt1 = ppr1.Value;
                //Point3d pt2 = ppr2.Value;

                Extents3d window = new Extents3d(
                    new Point3d(Math.Min(pt1.X, pt2.X), Math.Min(pt1.Y, pt2.Y), Math.Min(pt1.Z, pt2.Z)),
                    new Point3d(Math.Max(pt1.X, pt2.X), Math.Max(pt1.Y, pt2.Y), Math.Max(pt1.Z, pt2.Z))
                );

                // 2. 选择窗口内所有对象
                PromptSelectionResult psr = ed.SelectCrossingWindow(window.MinPoint, window.MaxPoint);
                if (psr.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("\n未选择到任何对象。");
                    return;
                }

                ObjectId[] selectedIds = psr.Value.GetObjectIds();

                if (selectedIds.Length == 0)
                {
                    ed.WriteMessage("\n选择集为空。");
                    return;
                }

                //读取block的属性名称
                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    foreach (ObjectId objId in selectedIds)
                    {
                        Entity entity = tr.GetObject(objId, OpenMode.ForRead) as Entity;
                        if (entity is BlockReference)
                        {
                            BlockReference blockRef = entity as BlockReference;
                            // 获取块引用所在的图层
                            string layerName = blockRef.Layer;
                            // 获取块的名称
                            string blockName = blockRef.Name;
                            // 输出块引用的信息
                            ed.WriteMessage("\n在图层 {0} 找到块引用: {1}", layerName, blockName);

                            // 遍历块引用中的所有属性
                            foreach (ObjectId attId in blockRef.AttributeCollection)
                            {
                                AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead);
                                if (attRef.Tag == GValues.BlockField_SemiProductCode)  //"图号"
                                {
                                    filename = attRef.TextString;
                                }
                                if (attRef.Tag == GValues.BlockField_SemiProductName ) //"零件名称"
                                {
                                    productName = attRef.TextString;
                                }
                            }
                        }
                    }
                }
                var destinationDirectory = Path.GetDirectoryName("c:\\dwg2upload\\");
                if (!Directory.Exists(destinationDirectory))
                {
                    Directory.CreateDirectory(destinationDirectory);
                }

                // 3. 保存选中对象的 Handle 到文件
                string desktopPath = Path.GetDirectoryName(doc.Name); //Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                //string handleFilePath = Path.Combine(desktopPath, "SelectedHandles.txt");
                string handleFilePath = Path.Combine(destinationDirectory, "SelectedHandles.txt");
                using (StreamWriter sw = new StreamWriter(handleFilePath, false))
                {
                    foreach (ObjectId id in selectedIds)
                    {
                        // 保存 Handle 字符串
                        sw.WriteLine(id.Handle.ToString());
                    }
                }
                ed.WriteMessage("\n已保存到文件");


                 string localFile = "";
                 string newDwgPath = "";
                 if (type == 3)
                 {
                     // 4. 创建新数据库，复制对象
                     newDwgPath = Path.Combine(desktopPath, filename.Trim() + "-other.dwg");
                     localFile = Path.Combine(destinationDirectory, filename.Trim() + "-other.dwg");
                 }
                 else if (type == 2)
                 {
                     newDwgPath = Path.Combine(desktopPath, filename.Trim() + "-material.dwg");
                     localFile = Path.Combine(destinationDirectory, filename.Trim() + "-material.dwg");
                 }
                 else {
                     // 4. 创建新数据库，复制对象
                     newDwgPath = Path.Combine(desktopPath, filename.Trim() + ".dwg");
                     localFile = Path.Combine(destinationDirectory, filename.Trim() + ".dwg");
                 }


                // 新建一个空数据库
                using (Database newDb = new Database(true, true))
                {
                    // 5. 读取 Handle 文件，转换为 ObjectId
                    List<ObjectId> idsToCopy = new List<ObjectId>();
                    using (StreamReader sr = new StreamReader(handleFilePath))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            Handle h = new Handle(Convert.ToInt64(line, 16)); // Handle是16进制字符串
                            ObjectId id = db.GetObjectId(false, h, 0);
                            if (!id.IsNull && !id.IsErased)
                            {
                                idsToCopy.Add(id);
                            }
                        }
                    }

                    if (idsToCopy.Count == 0)
                    {
                        ed.WriteMessage("\n根据 Handle 未找到任何有效对象。");
                        return;
                    }

                    // 转换 List<ObjectId> 到 ObjectIdCollection
                    ObjectIdCollection idsToCopyCollection = new ObjectIdCollection();
                    foreach (ObjectId id in selectedIds)
                    {
                        idsToCopyCollection.Add(id);
                    }
                    //using (Transaction newTr = newDb.TransactionManager.StartTransaction())
                    //{
                    //    try
                    //    {

                    //        newTr.Commit();
                    //    }
                    //    catch (System.Exception e)
                    //    {
                    //        newTr.Abort();
                    //        MessageBox.Show(e.Message);
                    //    }
                    //}
                    // 6. 使用 WblockCloneObjects 复制对象到新数据库
                    IdMapping mapping = new IdMapping();
                    db.WblockCloneObjects(
                        idsToCopyCollection,
                        newDb.CurrentSpaceId,
                        mapping,
                        DuplicateRecordCloning.Replace,
                        false
                    );

                    // 7. 保存新DWG文件DwgVersion.Current
                    newDb.SaveAs(localFile, DwgVersion.AC1800);
                    Thread.Sleep(5000); //延时5秒再复制文件
                    // 移动文件
                    try
                    {
                        File.Copy(localFile, newDwgPath,true);
                    } catch (IOException ex)
                    {
                        MessageBox.Show(ex.Message);
                    } 
                    catch (System.Exception e){
                        MessageBox.Show(e.Message);
                    }
                    
                    ed.WriteMessage("\n成功复制！");
                    BaigeBlockToPDF(pt1, pt2, type);
                    if (type == 2)
                    {
                        if (bomForm == null)
                        {
                            // 创建 Windows Form 窗口
                            bomForm = new BomForm();
                            bomForm.FormClosed += BomForm_FormClosed;
                            //bomForm.Disposed += BomForm_Disposed;
                        }
                        BasProductImport basProduct = new BasProductImport();
                        basProduct.code = filename;
                        basProduct.localAttachment = newDwgPath;
                        ed.WriteMessage("\n开始上传路径！" + filename + " / " + newDwgPath);
                        bomForm.BaigeUpdateMaterial(basProduct, new Action<string>(r =>
                        {
                            //ed.WriteMessage("\n上传路径成功！");
                        }));
                    }
                    if (type == 1)
                    {
                        if (bomForm == null)
                        {
                            // 创建 Windows Form 窗口
                            bomForm = new BomForm();
                            bomForm.FormClosed += BomForm_FormClosed;
                            //bomForm.Disposed += BomForm_Disposed;
                        }
                        BasProductImport basProduct = new BasProductImport();
                        basProduct.code = filename;
                        basProduct.name = productName;
                        basProduct.localAttachment = newDwgPath;
                        ed.WriteMessage("\n开始上传路径！" + filename + " / " + newDwgPath);
                        bomForm.BaigeUpdateProduct(basProduct, new Action<string>(r =>
                        {
                            //ed.WriteMessage("\n上传路径成功！");
                        }));
                    }
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\n发生异常！" + ex.Message);
            }
            
        }

        //20250729，后续调试使用
        //private readonly object _lockObject = new object();

        //public void CopyObjects()
        //{
        //    lock (_lockObject)
        //    {
        //        using (Transaction tr = db.TransactionManager.StartTransaction())
        //        {
        //            try
        //            {
        //                db.WblockCloneObjects(
        //                    idsToCopyCollection,
        //                    newDb.CurrentSpaceId,
        //                    mapping,
        //                    DuplicateRecordCloning.Replace,
        //                    true
        //                );
        //                tr.Commit();
        //            }
        //            catch (System.Exception ex)
        //            {
        //                tr.Abort();
        //                // 处理异常
        //                System.Diagnostics.Debug.WriteLine(ex.Message);
        //            }
        //        }
        //    }
        //}
        public void BaigeBlockToPDF(Point3d first1, Point3d second2)
        {
            getUserInfo();
            String OutPath = "";
            String processHandleId = "";
            Boolean checkProductCode = false;
            Directory.CreateDirectory(GValues.pdfPath);
            Dictionary<String, Dictionary<String, String>> tableDict = new Dictionary<string, Dictionary<string, string>>();
            SetObject setObject = new SetObject();
            setObject.initTableDictData(tableDict);
            // 判断文件是否存在
            //if (File.Exists(OutPath))
            //{
            //    try
            //    {
            //        // 尝试删除文件
            //        File.Delete(OutPath);
            //        outMsg.AddMsg("文件已删除。");
            //    }
            //    catch (IOException ex)
            //    {                    // IO异常处理
            //        outMsg.AddMsg("无法删除文件: " + ex.Message);
            //    }
            //}
            try
            {

                String BlockName;
                String PrinterName = "DWG To PDF.pc3";

                String PaperSize = "ISO_full_bleed_A4_(210.00_x_297.00_MM)";//"ISO_A4_(210.00_x_297.00_MM)";
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);

                //百舸begin
                //PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                //ppo.AllowNone = false;
                //PromptPointResult ppr = ed.GetPoint(ppo);
                //if (ppr.Status != PromptStatus.OK)
                //    return;
                //Point3d first1 = ppr.Value;
                //PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", first1);
                //ppr = ed.GetCorner(pco);
                //if (ppr.Status != PromptStatus.OK)
                //    return;
                //Point3d second2 = ppr.Value;
                //百舸end

                ///wcs 2 ucs
                ///
                //Vector3d vect = db.Ucsorg.GetVectorTo(new Point3d(0,0,0));
                //Matrix3d matWCS2UCS = Matrix3d.WorldToPlane(vect);
                //Point3d second = second1.TransformBy(matWCS2UCS);
                //Point3d first = first1.TransformBy(matWCS2UCS);
                ////


                //Matrix3d wcs2ucs = doc.Editor.CurrentUserCoordinateSystem.Inverse();
                //Point3d ucsPoint = worldPoint.TransformBy(wcs2ucs);

                //wcs 2 dcs
                //
                //
                // Gets the current view
                //ViewTableRecord acView = doc.Editor.GetCurrentView();
                ////Extents3d eExtents = new Extents3d(new Point3d(0, 0, 0), new Point3d(630, 445.5, 0));
                //Extents3d eExtents = new Extents3d(first, second);
                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                               acView.ViewDirection,
                //                               acView.Target) * matWCS2DCS;

                //// Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);

                //
                //ViewTableRecord acView = doc.Editor.GetCurrentView();

                //Extents3d eExtents = new Extents3d(first, second);

                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                                acView.ViewDirection,
                //                                acView.Target) * matWCS2DCS;

                ////Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);
                //var wcsWindow = new Extents2d(eExtents.MinPoint.X, eExtents.MinPoint.Y,
                //                                        eExtents.MaxPoint.X, eExtents.MaxPoint.Y);

                //
                // 获取当前视图方向
                Vector3d viewDir = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;

                // 获取当前视图位置
                Point3d viewPos = ed.GetCurrentView().Target;

                // 构造视图变换矩阵
                Matrix3d viewTransform = Matrix3d.WorldToPlane(viewDir).Inverse();
                //viewTransform = Matrix3d.Displacement(viewPos.GetAsVector()) * viewTransform;

                //// 将WCS坐标转换为DCS坐标
                Point3d first = first1.TransformBy(viewTransform);
                Point3d second = second2.TransformBy(viewTransform);


                ///====

                // Transform from UCS to DCS
                ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                double[] firres = new double[] { 0, 0, 0 };
                double[] secres = new double[] { 0, 0, 0 };
                // Transform the first point...
                acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                // ... and the second
                acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                // We can safely drop the Z-coord at this stage
                Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                //Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT");
                //Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    // We'll be plotting the current layout
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);

                    // 定义过滤条件，设置仅选择BlockReference

                    //SelectionFilter filter = new SelectionFilter(new TypedValue[]
                    //{
                    //    new TypedValue((int)DxfCode.Start, "TEXT") // "INSERT"代表图块引用
                    //});
                    // 使用选取窗口和过滤条件进行选择
                    PromptSelectionResult selectionResult = ed.SelectCrossingWindow(first, second);

                    // 检查选择结果
                    if (selectionResult.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\n未选择对象或操作取消。");
                        return;
                    }
                    //Dictionary<String, String> fieldDict = new Dictionary<string, string>();
                    selectedProcessName = "";
                    SelectionSet sSet = selectionResult.Value;
                    ObjectId[] selectedIds = sSet.GetObjectIds();  // 获取选择对象的ObjectiID数组.
                    foreach (ObjectId objId in selectedIds)
                    {
                        Entity entity = tr.GetObject(objId, OpenMode.ForRead) as Entity;
                        if (entity is Table)
                        {

                            Table table = entity as Table;
                            // 你现在可以使用table对象了
                            // ...
                            processHandleId = table.Handle.Value.ToString();
                            if (table.XData != null)
                            {
                                Dictionary<String, String> xDataDict = new Dictionary<string, string>();
                                String tableType = "none";
                                ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                // 遍历ResultBuffer以查看数据
                                foreach (TypedValue tv in rb)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            var a = tv.Value.ToString();
                                            ed.WriteMessage("\n APP Code :" + a);
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            var b = tv.Value.ToString();
                                            if (b.IndexOf("tableType:") != -1)
                                            {
                                                String[] cc = b.Split(':');
                                                if (cc[1] == "processSop")
                                                {
                                                    tableType = "processSop";
                                                    xDataDict["processSop"] = "true"; //SOP图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "processBom")
                                                {
                                                    tableType = "processBom";
                                                    xDataDict["processBom"] = "true"; //工艺图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "productBom")
                                                {
                                                    tableType = "productBom";
                                                    xDataDict["productBom"] = "true"; //产品图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                            }
                                            else if (b.IndexOf("processName:") != -1)
                                            {
                                                ed.WriteMessage("\n Process Name :" + b);
                                                String[] cc = b.Split(':');
                                                selectedProcessName = cc[1];
                                                xDataDict["processName"] = cc[1];
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            else if (b.IndexOf("productCode:") != -1)
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                String[] cc = b.Split(':');
                                                selectedProductCode = cc[1];
                                                xDataDict["productCode"] = cc[1];
                                                checkProductCode = true;
                                            }
                                            else
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                selectedProductCode = b;
                                                checkProductCode = true;
                                                xDataDict["productCode"] = b;
                                                xDataDict["oldTable"] = "true";
                                                tableType = "oldTable";
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            break;
                                        // 其他类型的DXF组码...

                                    }
                                }
                                tableDict[tableType] = xDataDict;
                            }
                            else
                            {
                                ed.WriteMessage("\n实体没有扩展数据！");
                            }
                        }

                    }
                    if (!checkProductCode)
                    {
                        ed.WriteMessage("\n选择框内没有定义工艺数据！");
                        return;
                    }
                    else
                    {
                        if (tableDict["productBom"]["productBom"] == "true" && tableDict["processBom"]["processBom"] == "false" && tableDict["processSop"]["processSop"] == "false")
                        {
                            ed.WriteMessage("\n选择框内没有定义工艺数据！");
                            return;
                        }
                    }
                    Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                    if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                    {
                        PlotEngine pe = PlotFactory.CreatePublishEngine();
                        using (pe)
                        {
                            PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true);
                            using (ppd)
                            {
                                int numSheet = 1;
                                // Setting up the PlotProgress dialog
                                ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                ppd.LowerPlotProgressRange = 0;
                                ppd.UpperPlotProgressRange = 100;
                                ppd.PlotProgressPos = 0;


                                ppd.OnBeginPlot();
                                ppd.IsVisible = true;
                                pe.BeginPlot(ppd, null);

                                ppd.StatusMsgString = "Plotting block 1";
                                ppd.OnBeginSheet(); //????
                                ppd.LowerSheetProgressRange = 0;
                                ppd.UpperSheetProgressRange = 100;
                                ppd.SheetProgressPos = 0;

                                PlotInfoValidator piv = new PlotInfoValidator();
                                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                PlotPageInfo ppi = new PlotPageInfo();
                                PlotInfo pi = new PlotInfo();
                                //BlockReference blk = gblk.BlockRef;
                                //Layout lo = btr.LayoutObj;

                                //// Getting coodinates of window to plot
                                //Extents3d ext = (Extents3d)blk.Bounds;
                                //Point3d first = ext.MaxPoint;
                                //Point3d second = ext.MinPoint;
                                //ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                                //double[] firres = new double[] { 0, 0, 0 };
                                //double[] secres = new double[] { 0, 0, 0 };
                                //acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                                //acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                                //Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                                // We need a PlotSettings object based on the layout settings which we then customize
                                PlotSettings ps = new PlotSettings(lo.ModelType);
                                //ps.PlotPlotStyles = true;
                                // Specify the plot options

                                LayoutManager.Current.CurrentLayout = lo.LayoutName;
                                pi.Layout = lo.Id;
                                ps.CopyFrom(lo);
                                ps.PrintLineweights = true;
                                ps.PlotTransparency = false;
                                ps.PlotPlotStyles = true;
                                ps.DrawViewportsFirst = true;
                                ps.ShowPlotStyles = true;
                                //PlotStyleTable = GetVauleFromArray("CtbThinnerLinesName")
                                // The PlotSettingsValidator helps create a valid PlotSettings object
                                PlotSettingsValidator psv = PlotSettingsValidator.Current;
                                psv.SetPlotConfigurationName(ps, PrinterName, PaperSize);
                                psv.RefreshLists(ps);
                                psv.SetPlotWindowArea(ps, window);
                                psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                                psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                                psv.SetCurrentStyleSheet(ps, "monochrome.ctb");
                                ////
                                //var e = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("PSTYLEMODE");
                                //var a = db.PlotStyleMode;
                                //var b = psv.GetPlotStyleSheetList();
                                //foreach (String CTB in b)
                                //{
                                //    var c = CTB;
                                //}
                                //if (a)
                                //{
                                //     psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

                                //}
                                //else
                                //{
                                //    psv.SetCurrentStyleSheet(ps, "monochrome.stb");
                                //}


                                psv.SetPlotCentered(ps, true);

                                pi.OverrideSettings = ps;
                                piv.Validate(pi);
                                if (selectedProcessName != "")
                                {
                                    OutPath = GValues.pdfPath + "\\" + selectedProductCode + "-process-" + selectedProcessName + "-" + tableDict["processSop"]["tableHandleId"] + ".pdf";
                                }
                                else
                                {
                                    OutPath = GValues.pdfPath + "\\" + selectedProductCode + ".pdf";
                                }

                                pe.BeginDocument(pi, doc.Name, null, 1, true, OutPath); // Create document for the first page

                                // Plot the window
                                pe.BeginPage(ppi, pi, true, null);
                                pe.BeginGenerateGraphics(null);
                                ppd.SheetProgressPos = 50;
                                pe.EndGenerateGraphics(null);

                                // Finish the sheet
                                pe.EndPage(null);
                                ppd.SheetProgressPos = 100;
                                ppd.PlotProgressPos = 100; //+= Convert.ToInt32(100 / BlocksToPlot.Count);
                                ppd.OnEndSheet();
                                // Finish the document and finish the plot
                                pe.EndDocument(null);

                                ppd.PlotProgressPos = 100;
                                ppd.OnEndPlot();
                                pe.EndPlot(null);
                                ed.WriteMessage("\nPlot completed successfully!\n\n");
                                ps.Dispose();
                                pe.Dispose();
                                ppd.Dispose();
                            }
                        }
                        //Task.Delay(2000);

                        //doc.CloseAndDiscard();

                        // 关闭绘图过程
                        //PlotFactory.ProcessPlotState = PlotState.Cancel;
                    }
                    else
                    {
                        ed.WriteMessage("\nAnother plot is in progress.\n\n");
                    }
                    tr.Commit();
                    tr.Dispose();
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.PlotSettings): DisposableWrapper
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.ViewTableRecord): DisposableWrapper

                }
                //Application.SetSystemVariable("BACKGROUNDPLOT", SysVarBackPlot);
                //if (this.pdfform != null)
                //{
                //    this.pdfform.Close();
                //    this.pdfform = null;

                //}
                //pdfform = new PdfProgressForm(selectedProductCode, new Action<int>((r) =>
                //{
                //    if (r == 1)
                //    {
                //        //uploadPdf();
                //        //this.pdfform.Close();
                //    }
                //    else
                //    {
                //        //ed.WriteMessage("\n上传pdf失败");
                //    }
                //}));
                //// 显示 Windows Form 窗口
                //Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, pdfform);
                //pdfform.beginProcess();

                //for (int i = 0; i <= 100; i++)
                //{
                //    SimpleProgressBar bar = new SimpleProgressBar();
                //    bar.Show();
                //    bar.UpdateProgress(100);

                //    //Thread.Sleep(100); // 模拟任务的执行时间
                //    Task.Delay(TimeSpan.FromSeconds(2)).Wait(); //等待2秒
                //    String filePath = GValues.pdfPath + "\\selectDWGWindow.pdf";
                //    // 判断文件是否存在
                //    if (File.Exists(filePath))
                //    {
                //        bar.Close();
                //        DialogResult res = MessageBox.Show("PDF文件已经生成，确认要上传吗？", "上传提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                //        if (res == DialogResult.OK)  //1为确定，2为取消,...
                //        {
                //            //按OK后，执行语句；
                //            if (checkProductCode)
                //            {
                //                uploadPdf();
                //            }
                //        }
                //        if (res == DialogResult.Cancel)  //1为确定，2为取消,...
                //        {
                //            //按Cancel后，执行语句；
                //        }

                //        break;
                //        //Thread.Sleep(2000);
                //        //uploadPdf();
                //        //ed.WriteMessage("上传完成！");
                //    }
                // }

            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {

            }
            finally
            {

            }


        }

        private void KeerdaGetProductCode()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            BasProductImport importProduct = new BasProductImport();
            string baigeProductCode = "";
            string materialHeigh = "";
            string materialSpec = "";
            string materialFace = "";
            string dwgPath = Path.GetDirectoryName(doc.Name);
            importProduct.customerCode = "C001";
            importProduct.unitName = "PCS";
            importProduct.productVer = "A";
            importProduct.productTypeName = "半成品";
            importProduct.currencyName = "人民币";

            // 选择块
            PromptEntityOptions blockOptions = new PromptEntityOptions("\n请选择一个块: ");
            blockOptions.SetRejectMessage("\n选择的对象不是块。");
            blockOptions.AddAllowedClass(typeof(BlockReference), true);

            PromptEntityResult blockResult = ed.GetEntity(blockOptions);
            if (blockResult.Status != PromptStatus.OK)
                return;

            ObjectId blockId = blockResult.ObjectId;

            // 获取块的定义
            using (Transaction trans = doc.TransactionManager.StartTransaction())
            {
                BlockReference blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead);
                if (blockRef != null)
                {
                    string blockName = blockRef.Name;
                    importProduct.cadHandleId = blockRef.Handle.Value.ToString();
                    //baigeBlockCadHandleId = blockRef.Handle.Value.ToString();
                    // 输出块引用的信息
                    ed.WriteMessage("\n找到块引用: {0}", blockName);

                    // 遍历块引用中的所有属性
                    foreach (ObjectId attId in blockRef.AttributeCollection)
                    {
                        AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead);
                        //if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                        //{
                        //    baigeProductCode = attRef.TextString;
                        //    importProduct.code = attRef.TextString;
                        //    importProduct.custCode = attRef.TextString;
                        //    importProduct.localAttachment = dwgPath + "/" + attRef.TextString + ".dwg";
                        //}
                        if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                        {
                            baigeProductCode = attRef.TextString;
                            importProduct.code = attRef.TextString;
                            importProduct.custCode = attRef.TextString;
                            importProduct.localAttachment = dwgPath + "/" + attRef.TextString + ".dwg";
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductName) //"零件名称"
                        {
                            importProduct.name = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_ProductName) //"产品名称"
                        {
                            importProduct.mainName = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_CaiLiao) //"材料"
                        {
                            materialSpec = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_CaiHou || attRef.Tag == GValues.BlockField_HouDu) //"材厚" "厚度"
                        {
                            materialHeigh = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SurfaceChuli) //"表面处理"
                        {
                            materialFace = attRef.TextString;
                        }
                        ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                    }
                }

                trans.Commit();
            }
            //ed.WriteMessage("\n块内容已导出到 {newDwgPath}");
            if (baigeProductCode == null || baigeProductCode == "")
            {
                ed.WriteMessage("\n块内容没定义图号！");
            }
            else
            {
                KeerdaPlotBlockColToPDF(baigeProductCode);
            }
        }

        private void KeerdaGetProductCodePNG()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            BasProductImport importProduct = new BasProductImport();
            string baigeProductCode = "";
            string materialHeigh = "";
            string materialSpec = "";
            string materialFace = "";
            string dwgPath = Path.GetDirectoryName(doc.Name);
            importProduct.customerCode = "C001";
            importProduct.unitName = "PCS";
            importProduct.productVer = "A";
            importProduct.productTypeName = "半成品";
            importProduct.currencyName = "人民币";

            // 选择块
            PromptEntityOptions blockOptions = new PromptEntityOptions("\n请选择一个块: ");
            blockOptions.SetRejectMessage("\n选择的对象不是块。");
            blockOptions.AddAllowedClass(typeof(BlockReference), true);

            PromptEntityResult blockResult = ed.GetEntity(blockOptions);
            if (blockResult.Status != PromptStatus.OK)
                return;

            ObjectId blockId = blockResult.ObjectId;

            // 获取块的定义
            using (Transaction trans = doc.TransactionManager.StartTransaction())
            {
                BlockReference blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead);
                if (blockRef != null)
                {
                    string blockName = blockRef.Name;
                    importProduct.cadHandleId = blockRef.Handle.Value.ToString();
                    //baigeBlockCadHandleId = blockRef.Handle.Value.ToString();
                    // 输出块引用的信息
                    ed.WriteMessage("\n找到块引用: {0}", blockName);

                    // 遍历块引用中的所有属性
                    foreach (ObjectId attId in blockRef.AttributeCollection)
                    {
                        AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead);
                        //if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                        //{
                        //    baigeProductCode = attRef.TextString;
                        //    importProduct.code = attRef.TextString;
                        //    importProduct.custCode = attRef.TextString;
                        //    importProduct.localAttachment = dwgPath + "/" + attRef.TextString + ".dwg";
                        //}
                        if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                        {
                            baigeProductCode = attRef.TextString;
                            importProduct.code = attRef.TextString;
                            importProduct.custCode = attRef.TextString;
                            importProduct.localAttachment = dwgPath + "/" + attRef.TextString + ".dwg";
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductName) //"零件名称"
                        {
                            importProduct.name = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_ProductName) //"产品名称"
                        {
                            importProduct.mainName = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_CaiLiao) //"材料"
                        {
                            materialSpec = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_CaiHou || attRef.Tag == GValues.BlockField_HouDu) //"材厚" "厚度"
                        {
                            materialHeigh = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SurfaceChuli) //"表面处理"
                        {
                            materialFace = attRef.TextString;
                        }
                        ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                    }
                }

                trans.Commit();
            }
            //ed.WriteMessage("\n块内容已导出到 {newDwgPath}");
            if (baigeProductCode == null || baigeProductCode == "")
            {
                ed.WriteMessage("\n块内容没定义图号！");
            }
            else
            {
                KeerdaPlotBlockColToPNG(baigeProductCode);
            }
        }

        private void KeerdaPlotBlockColToPDF(string filename)
        {
            InitDomainConfig();
            getUserInfo();
            String OutPath = "";
            String processHandleId = "";
            Boolean checkProductCode = false;
            Directory.CreateDirectory(GValues.pdfPath);
            Dictionary<String, Dictionary<String, String>> tableDict = new Dictionary<string, Dictionary<string, string>>();
            SetObject setObject = new SetObject();
            setObject.initTableDictData(tableDict);
            // 判断文件是否存在
            //if (File.Exists(OutPath))
            //{
            //    try
            //    {
            //        // 尝试删除文件
            //        File.Delete(OutPath);
            //        outMsg.AddMsg("文件已删除。");
            //    }
            //    catch (IOException ex)
            //    {                    // IO异常处理
            //        outMsg.AddMsg("无法删除文件: " + ex.Message);
            //    }
            //}
            try
            {

                String BlockName;
                String PrinterName = "DWG To PDF.pc3";

                String PaperSize = "ISO_full_bleed_A4_(210.00_x_297.00_MM)";//"ISO_A4_(210.00_x_297.00_MM)";
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                ppo.AllowNone = false;
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d first1 = ppr.Value;
                PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", first1);
                ppr = ed.GetCorner(pco);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d second2 = ppr.Value;

                ///wcs 2 ucs
                ///
                //Vector3d vect = db.Ucsorg.GetVectorTo(new Point3d(0,0,0));
                //Matrix3d matWCS2UCS = Matrix3d.WorldToPlane(vect);
                //Point3d second = second1.TransformBy(matWCS2UCS);
                //Point3d first = first1.TransformBy(matWCS2UCS);
                ////


                //Matrix3d wcs2ucs = doc.Editor.CurrentUserCoordinateSystem.Inverse();
                //Point3d ucsPoint = worldPoint.TransformBy(wcs2ucs);

                //wcs 2 dcs
                //
                //
                // Gets the current view
                //ViewTableRecord acView = doc.Editor.GetCurrentView();
                ////Extents3d eExtents = new Extents3d(new Point3d(0, 0, 0), new Point3d(630, 445.5, 0));
                //Extents3d eExtents = new Extents3d(first, second);
                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                               acView.ViewDirection,
                //                               acView.Target) * matWCS2DCS;

                //// Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);

                //
                //ViewTableRecord acView = doc.Editor.GetCurrentView();

                //Extents3d eExtents = new Extents3d(first, second);

                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                                acView.ViewDirection,
                //                                acView.Target) * matWCS2DCS;

                ////Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);
                //var wcsWindow = new Extents2d(eExtents.MinPoint.X, eExtents.MinPoint.Y,
                //                                        eExtents.MaxPoint.X, eExtents.MaxPoint.Y);

                //
                // 获取当前视图方向
                Vector3d viewDir = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;

                // 获取当前视图位置
                Point3d viewPos = ed.GetCurrentView().Target;

                // 构造视图变换矩阵
                Matrix3d viewTransform = Matrix3d.WorldToPlane(viewDir).Inverse();
                //viewTransform = Matrix3d.Displacement(viewPos.GetAsVector()) * viewTransform;

                //// 将WCS坐标转换为DCS坐标
                Point3d first = first1.TransformBy(viewTransform);
                Point3d second = second2.TransformBy(viewTransform);


                ///====

                // Transform from UCS to DCS
                ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                double[] firres = new double[] { 0, 0, 0 };
                double[] secres = new double[] { 0, 0, 0 };
                // Transform the first point...
                acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                // ... and the second
                acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                // We can safely drop the Z-coord at this stage
                Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                //Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT");
                //Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    // We'll be plotting the current layout
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);

                    // 定义过滤条件，设置仅选择BlockReference

                    //SelectionFilter filter = new SelectionFilter(new TypedValue[]
                    //{
                    //    new TypedValue((int)DxfCode.Start, "TEXT") // "INSERT"代表图块引用
                    //});
                    // 使用选取窗口和过滤条件进行选择
                    PromptSelectionResult selectionResult = ed.SelectCrossingWindow(first, second);

                    // 检查选择结果
                    if (selectionResult.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\n未选择对象或操作取消。");
                        return;
                    }
                    //Dictionary<String, String> fieldDict = new Dictionary<string, string>();
                    selectedProcessName = "";
                    SelectionSet sSet = selectionResult.Value;
                    ObjectId[] selectedIds = sSet.GetObjectIds();  // 获取选择对象的ObjectiID数组.
                    foreach (ObjectId objId in selectedIds)
                    {
                        Entity entity = tr.GetObject(objId, OpenMode.ForRead) as Entity;
                        if (entity is Table)
                        {

                            Table table = entity as Table;
                            // 你现在可以使用table对象了
                            // ...
                            processHandleId = table.Handle.Value.ToString();
                            if (table.XData != null)
                            {
                                Dictionary<String, String> xDataDict = new Dictionary<string, string>();
                                String tableType = "none";
                                ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                // 遍历ResultBuffer以查看数据
                                foreach (TypedValue tv in rb)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            var a = tv.Value.ToString();
                                            ed.WriteMessage("\n APP Code :" + a);
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            var b = tv.Value.ToString();
                                            if (b.IndexOf("tableType:") != -1)
                                            {
                                                String[] cc = b.Split(':');
                                                if (cc[1] == "processSop")
                                                {
                                                    tableType = "processSop";
                                                    xDataDict["processSop"] = "true"; //SOP图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "processBom")
                                                {
                                                    tableType = "processBom";
                                                    xDataDict["processBom"] = "true"; //工艺图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "productBom")
                                                {
                                                    tableType = "productBom";
                                                    xDataDict["productBom"] = "true"; //产品图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                            }
                                            else if (b.IndexOf("processName:") != -1)
                                            {
                                                ed.WriteMessage("\n Process Name :" + b);
                                                String[] cc = b.Split(':');
                                                selectedProcessName = cc[1];
                                                xDataDict["processName"] = cc[1];
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            else if (b.IndexOf("productCode:") != -1)
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                String[] cc = b.Split(':');
                                                selectedProductCode = cc[1];
                                                xDataDict["productCode"] = cc[1];
                                                checkProductCode = true;
                                            }
                                            else
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                selectedProductCode = b;
                                                checkProductCode = true;
                                                xDataDict["productCode"] = b;
                                                xDataDict["oldTable"] = "true";
                                                tableType = "oldTable";
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            break;
                                        // 其他类型的DXF组码...

                                    }
                                }
                                tableDict[tableType] = xDataDict;
                            }
                            else
                            {
                                ed.WriteMessage("\n实体没有扩展数据！");
                            }
                        }

                    }
                    //if (!checkProductCode)
                    //{
                    //    ed.WriteMessage("\n选择框内没有定义工艺数据！");
                    //    return;
                    //}
                    //else
                    //{
                    //    if (tableDict["productBom"]["productBom"] == "true" && tableDict["processBom"]["processBom"] == "false" && tableDict["processSop"]["processSop"] == "false")
                    //    {
                    //        ed.WriteMessage("\n选择框内没有定义工艺数据！");
                    //        return;
                    //    }
                    //}
                    Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                    if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                    {
                        PlotEngine pe = PlotFactory.CreatePublishEngine();
                        using (pe)
                        {
                            PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true);
                            using (ppd)
                            {
                                int numSheet = 1;
                                // Setting up the PlotProgress dialog
                                ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                ppd.LowerPlotProgressRange = 0;
                                ppd.UpperPlotProgressRange = 100;
                                ppd.PlotProgressPos = 0;


                                ppd.OnBeginPlot();
                                ppd.IsVisible = true;
                                pe.BeginPlot(ppd, null);

                                ppd.StatusMsgString = "Plotting block 1";
                                ppd.OnBeginSheet(); //????
                                ppd.LowerSheetProgressRange = 0;
                                ppd.UpperSheetProgressRange = 100;
                                ppd.SheetProgressPos = 0;

                                PlotInfoValidator piv = new PlotInfoValidator();
                                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                PlotPageInfo ppi = new PlotPageInfo();
                                PlotInfo pi = new PlotInfo();
                                //BlockReference blk = gblk.BlockRef;
                                //Layout lo = btr.LayoutObj;

                                //// Getting coodinates of window to plot
                                //Extents3d ext = (Extents3d)blk.Bounds;
                                //Point3d first = ext.MaxPoint;
                                //Point3d second = ext.MinPoint;
                                //ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                                //double[] firres = new double[] { 0, 0, 0 };
                                //double[] secres = new double[] { 0, 0, 0 };
                                //acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                                //acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                                //Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                                // We need a PlotSettings object based on the layout settings which we then customize
                                PlotSettings ps = new PlotSettings(lo.ModelType);
                                //ps.PlotPlotStyles = true;
                                // Specify the plot options

                                LayoutManager.Current.CurrentLayout = lo.LayoutName;
                                pi.Layout = lo.Id;
                                ps.CopyFrom(lo);
                                ps.PrintLineweights = true;
                                ps.PlotTransparency = false;
                                ps.PlotPlotStyles = true;
                                ps.DrawViewportsFirst = true;
                                ps.ShowPlotStyles = true;
                                //PlotStyleTable = GetVauleFromArray("CtbThinnerLinesName")
                                // The PlotSettingsValidator helps create a valid PlotSettings object
                                PlotSettingsValidator psv = PlotSettingsValidator.Current;
                                psv.SetPlotConfigurationName(ps, PrinterName, PaperSize);
                                //psv.SetPlotConfigurationName(ps, "PublishToWeb PNG.pc3", null);
                                psv.RefreshLists(ps);
                                psv.SetPlotWindowArea(ps, window);
                                psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                                psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                                psv.SetCurrentStyleSheet(ps, "monochrome.ctb");
                                ////
                                //var e = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("PSTYLEMODE");
                                //var a = db.PlotStyleMode;
                                //var b = psv.GetPlotStyleSheetList();
                                //foreach (String CTB in b)
                                //{
                                //    var c = CTB;
                                //}
                                //if (a)
                                //{
                                //     psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

                                //}
                                //else
                                //{
                                //    psv.SetCurrentStyleSheet(ps, "monochrome.stb");
                                //}


                                psv.SetPlotCentered(ps, true);

                                pi.OverrideSettings = ps;
                                piv.Validate(pi);
                                //if (selectedProcessName != "")
                                //{
                                //    OutPath = GValues.pdfPath + "\\" + filename + "-process-" + selectedProcessName + "-" + tableDict["processSop"]["tableHandleId"] + ".pdf";
                                //}
                                //else
                                //{
                                //    OutPath = GValues.pdfPath + "\\" + filename + ".pdf";
                                //}
                                OutPath = GValues.pdfPath + "\\" + filename + ".pdf";
                                pe.BeginDocument(pi, doc.Name, null, 1, true, OutPath); // Create document for the first page

                                // Plot the window
                                pe.BeginPage(ppi, pi, true, null);
                                pe.BeginGenerateGraphics(null);
                                ppd.SheetProgressPos = 50;
                                pe.EndGenerateGraphics(null);

                                // Finish the sheet
                                pe.EndPage(null);
                                ppd.SheetProgressPos = 100;
                                ppd.PlotProgressPos = 100; //+= Convert.ToInt32(100 / BlocksToPlot.Count);
                                ppd.OnEndSheet();
                                // Finish the document and finish the plot
                                pe.EndDocument(null);

                                ppd.PlotProgressPos = 100;
                                ppd.OnEndPlot();
                                pe.EndPlot(null);
                                ed.WriteMessage("\nPlot completed successfully!\n\n");
                                ps.Dispose();
                                pe.Dispose();
                                ppd.Dispose();
                            }
                        }
                        //Task.Delay(2000);

                        //doc.CloseAndDiscard();

                        // 关闭绘图过程
                        //PlotFactory.ProcessPlotState = PlotState.Cancel;
                    }
                    else
                    {
                        ed.WriteMessage("\nAnother plot is in progress.\n\n");
                    }
                    tr.Commit();
                    tr.Dispose();
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.PlotSettings): DisposableWrapper
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.ViewTableRecord): DisposableWrapper

                }
                //Application.SetSystemVariable("BACKGROUNDPLOT", SysVarBackPlot);
                //if (this.pdfform != null)
                //{
                //    this.pdfform.Close();
                //    this.pdfform = null;

                //}
                //pdfform = new PdfProgressForm(selectedProductCode, new Action<int>((r) =>
                //{
                //    if (r == 1)
                //    {
                //        //uploadPdf();
                //        //this.pdfform.Close();
                //    }
                //    else
                //    {
                //        //ed.WriteMessage("\n上传pdf失败");
                //    }
                //}));
                //// 显示 Windows Form 窗口
                //Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, pdfform);
                //pdfform.beginProcess();

                //for (int i = 0; i <= 100; i++)
                //{
                //    SimpleProgressBar bar = new SimpleProgressBar();
                //    bar.Show();
                //    bar.UpdateProgress(100);

                //    //Thread.Sleep(100); // 模拟任务的执行时间
                //    Task.Delay(TimeSpan.FromSeconds(2)).Wait(); //等待2秒
                //    String filePath = GValues.pdfPath + "\\selectDWGWindow.pdf";
                //    // 判断文件是否存在
                //    if (File.Exists(filePath))
                //    {
                //        bar.Close();
                //        DialogResult res = MessageBox.Show("PDF文件已经生成，确认要上传吗？", "上传提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                //        if (res == DialogResult.OK)  //1为确定，2为取消,...
                //        {
                //            //按OK后，执行语句；
                //            if (checkProductCode)
                //            {
                //                uploadPdf();
                //            }
                //        }
                //        if (res == DialogResult.Cancel)  //1为确定，2为取消,...
                //        {
                //            //按Cancel后，执行语句；
                //        }

                //        break;
                //        //Thread.Sleep(2000);
                //        //uploadPdf();
                //        //ed.WriteMessage("上传完成！");
                //    }
                // }

            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {

            }
            finally
            {

            }



        }

        private void KeerdaPlotBlockColToPNG(string filename)
        {
            InitDomainConfig();
            getUserInfo();
            String OutPath = "";

            string directoryPath = GValues.pdfPath + "\\png";

            // 检查目录是否存在
            if (!Directory.Exists(directoryPath))
            {
                // 目录不存在，创建目录
                Directory.CreateDirectory(directoryPath);
            }

            String processHandleId = "";
            Boolean checkProductCode = false;
            Directory.CreateDirectory(GValues.pdfPath);
            Dictionary<String, Dictionary<String, String>> tableDict = new Dictionary<string, Dictionary<string, string>>();
            SetObject setObject = new SetObject();
            setObject.initTableDictData(tableDict);
            // 判断文件是否存在
            //if (File.Exists(OutPath))
            //{
            //    try
            //    {
            //        // 尝试删除文件
            //        File.Delete(OutPath);
            //        outMsg.AddMsg("文件已删除。");
            //    }
            //    catch (IOException ex)
            //    {                    // IO异常处理
            //        outMsg.AddMsg("无法删除文件: " + ex.Message);
            //    }
            //}
            try
            {

                String BlockName;
                String PrinterName = "DWG To PDF.pc3";
                //String PrinterName = "PublishToWeb PNG.pc3";

                String PaperSize = "ISO_full_bleed_A4_(210.00_x_297.00_MM)"; //"ISO_full_bleed_A4_(210.00_x_297.00_MM)";//"ISO_A4_(210.00_x_297.00_MM)";
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                ppo.AllowNone = false;
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d first1 = ppr.Value;
                PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", first1);
                ppr = ed.GetCorner(pco);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d second2 = ppr.Value;

                ///wcs 2 ucs
                ///
                //Vector3d vect = db.Ucsorg.GetVectorTo(new Point3d(0,0,0));
                //Matrix3d matWCS2UCS = Matrix3d.WorldToPlane(vect);
                //Point3d second = second1.TransformBy(matWCS2UCS);
                //Point3d first = first1.TransformBy(matWCS2UCS);
                ////


                //Matrix3d wcs2ucs = doc.Editor.CurrentUserCoordinateSystem.Inverse();
                //Point3d ucsPoint = worldPoint.TransformBy(wcs2ucs);

                //wcs 2 dcs
                //
                //
                // Gets the current view
                //ViewTableRecord acView = doc.Editor.GetCurrentView();
                ////Extents3d eExtents = new Extents3d(new Point3d(0, 0, 0), new Point3d(630, 445.5, 0));
                //Extents3d eExtents = new Extents3d(first, second);
                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                               acView.ViewDirection,
                //                               acView.Target) * matWCS2DCS;

                //// Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);

                //
                //ViewTableRecord acView = doc.Editor.GetCurrentView();

                //Extents3d eExtents = new Extents3d(first, second);

                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                                acView.ViewDirection,
                //                                acView.Target) * matWCS2DCS;

                ////Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);
                //var wcsWindow = new Extents2d(eExtents.MinPoint.X, eExtents.MinPoint.Y,
                //                                        eExtents.MaxPoint.X, eExtents.MaxPoint.Y);

                //
                // 获取当前视图方向
                Vector3d viewDir = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;

                // 获取当前视图位置
                Point3d viewPos = ed.GetCurrentView().Target;

                // 构造视图变换矩阵
                Matrix3d viewTransform = Matrix3d.WorldToPlane(viewDir).Inverse();
                //viewTransform = Matrix3d.Displacement(viewPos.GetAsVector()) * viewTransform;

                //// 将WCS坐标转换为DCS坐标
                Point3d first = first1.TransformBy(viewTransform);
                Point3d second = second2.TransformBy(viewTransform);


                ///====

                // Transform from UCS to DCS
                ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                double[] firres = new double[] { 0, 0, 0 };
                double[] secres = new double[] { 0, 0, 0 };
                // Transform the first point...
                acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                // ... and the second
                acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                // We can safely drop the Z-coord at this stage
                Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                //Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT");
                //Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    // We'll be plotting the current layout
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);

                    // 定义过滤条件，设置仅选择BlockReference

                    //SelectionFilter filter = new SelectionFilter(new TypedValue[]
                    //{
                    //    new TypedValue((int)DxfCode.Start, "TEXT") // "INSERT"代表图块引用
                    //});
                    // 使用选取窗口和过滤条件进行选择
                    PromptSelectionResult selectionResult = ed.SelectCrossingWindow(first, second);

                    // 检查选择结果
                    if (selectionResult.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\n未选择对象或操作取消。");
                        return;
                    }
                    //Dictionary<String, String> fieldDict = new Dictionary<string, string>();
                    selectedProcessName = "";
                    SelectionSet sSet = selectionResult.Value;
                    ObjectId[] selectedIds = sSet.GetObjectIds();  // 获取选择对象的ObjectiID数组.
                    foreach (ObjectId objId in selectedIds)
                    {
                        Entity entity = tr.GetObject(objId, OpenMode.ForRead) as Entity;
                        if (entity is Table)
                        {

                            Table table = entity as Table;
                            // 你现在可以使用table对象了
                            // ...
                            processHandleId = table.Handle.Value.ToString();
                            if (table.XData != null)
                            {
                                Dictionary<String, String> xDataDict = new Dictionary<string, string>();
                                String tableType = "none";
                                ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                // 遍历ResultBuffer以查看数据
                                foreach (TypedValue tv in rb)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            var a = tv.Value.ToString();
                                            ed.WriteMessage("\n APP Code :" + a);
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            var b = tv.Value.ToString();
                                            if (b.IndexOf("tableType:") != -1)
                                            {
                                                String[] cc = b.Split(':');
                                                if (cc[1] == "processSop")
                                                {
                                                    tableType = "processSop";
                                                    xDataDict["processSop"] = "true"; //SOP图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "processBom")
                                                {
                                                    tableType = "processBom";
                                                    xDataDict["processBom"] = "true"; //工艺图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "productBom")
                                                {
                                                    tableType = "productBom";
                                                    xDataDict["productBom"] = "true"; //产品图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                            }
                                            else if (b.IndexOf("processName:") != -1)
                                            {
                                                ed.WriteMessage("\n Process Name :" + b);
                                                String[] cc = b.Split(':');
                                                selectedProcessName = cc[1];
                                                xDataDict["processName"] = cc[1];
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            else if (b.IndexOf("productCode:") != -1)
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                String[] cc = b.Split(':');
                                                selectedProductCode = cc[1];
                                                xDataDict["productCode"] = cc[1];
                                                checkProductCode = true;
                                            }
                                            else
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                selectedProductCode = b;
                                                checkProductCode = true;
                                                xDataDict["productCode"] = b;
                                                xDataDict["oldTable"] = "true";
                                                tableType = "oldTable";
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            break;
                                        // 其他类型的DXF组码...

                                    }
                                }
                                tableDict[tableType] = xDataDict;
                            }
                            else
                            {
                                ed.WriteMessage("\n实体没有扩展数据！");
                            }
                        }

                    }
                    //if (!checkProductCode)
                    //{
                    //    ed.WriteMessage("\n选择框内没有定义工艺数据！");
                    //    return;
                    //}
                    //else
                    //{
                    //    if (tableDict["productBom"]["productBom"] == "true" && tableDict["processBom"]["processBom"] == "false" && tableDict["processSop"]["processSop"] == "false")
                    //    {
                    //        ed.WriteMessage("\n选择框内没有定义工艺数据！");
                    //        return;
                    //    }
                    //}
                    Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                    if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                    {
                        PlotEngine pe = PlotFactory.CreatePublishEngine();
                        using (pe)
                        {
                            PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true);
                            using (ppd)
                            {
                                int numSheet = 1;
                                // Setting up the PlotProgress dialog
                                ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                ppd.LowerPlotProgressRange = 0;
                                ppd.UpperPlotProgressRange = 100;
                                ppd.PlotProgressPos = 0;


                                ppd.OnBeginPlot();
                                ppd.IsVisible = true;
                                pe.BeginPlot(ppd, null);

                                ppd.StatusMsgString = "Plotting block 1";
                                ppd.OnBeginSheet(); //????
                                ppd.LowerSheetProgressRange = 0;
                                ppd.UpperSheetProgressRange = 100;
                                ppd.SheetProgressPos = 0;

                                PlotInfoValidator piv = new PlotInfoValidator();
                                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                PlotPageInfo ppi = new PlotPageInfo();
                                PlotInfo pi = new PlotInfo();
                                //BlockReference blk = gblk.BlockRef;
                                //Layout lo = btr.LayoutObj;

                                //// Getting coodinates of window to plot
                                //Extents3d ext = (Extents3d)blk.Bounds;
                                //Point3d first = ext.MaxPoint;
                                //Point3d second = ext.MinPoint;
                                //ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                                //double[] firres = new double[] { 0, 0, 0 };
                                //double[] secres = new double[] { 0, 0, 0 };
                                //acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                                //acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                                //Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                                // We need a PlotSettings object based on the layout settings which we then customize
                                PlotSettings ps = new PlotSettings(lo.ModelType);
                                //ps.PlotPlotStyles = true;
                                // Specify the plot options

                                LayoutManager.Current.CurrentLayout = lo.LayoutName;
                                pi.Layout = lo.Id;
                                ps.CopyFrom(lo);
                                ps.PrintLineweights = true;
                                ps.PlotTransparency = false;
                                ps.PlotPlotStyles = true;
                                ps.DrawViewportsFirst = true;
                                ps.ShowPlotStyles = true;
                                //PlotStyleTable = GetVauleFromArray("CtbThinnerLinesName")
                                // The PlotSettingsValidator helps create a valid PlotSettings object
                                PlotSettingsValidator psv = PlotSettingsValidator.Current;
                                psv.SetPlotConfigurationName(ps, PrinterName, PaperSize);
                                //psv.SetPlotConfigurationName(ps, PrinterName, null);
                                psv.RefreshLists(ps);
                                psv.SetPlotWindowArea(ps, window);
                                psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                                psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                                psv.SetCurrentStyleSheet(ps, "monochrome.ctb");
                                ////
                                //var e = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("PSTYLEMODE");
                                //var a = db.PlotStyleMode;
                                //var b = psv.GetPlotStyleSheetList();
                                //foreach (String CTB in b)
                                //{
                                //    var c = CTB;
                                //}
                                //if (a)
                                //{
                                //     psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

                                //}
                                //else
                                //{
                                //    psv.SetCurrentStyleSheet(ps, "monochrome.stb");
                                //}


                                psv.SetPlotCentered(ps, true);

                                pi.OverrideSettings = ps;
                                piv.Validate(pi);
                                //if (selectedProcessName != "")
                                //{
                                //    OutPath = GValues.pdfPath + "\\" + filename + "-process-" + selectedProcessName + "-" + tableDict["processSop"]["tableHandleId"] + ".pdf";
                                //}
                                //else
                                //{
                                //    OutPath = GValues.pdfPath + "\\" + filename + ".pdf";
                                //}
                                //OutPath = GValues.pdfPath + "\\" + filename + ".pdf";
                                OutPath = GValues.pdfPath + "\\png\\" + filename + ".pdf";
                                pe.BeginDocument(pi, doc.Name, null, 1, true, OutPath); // Create document for the first page

                                // Plot the window
                                pe.BeginPage(ppi, pi, true, null);
                                pe.BeginGenerateGraphics(null);
                                ppd.SheetProgressPos = 50;
                                pe.EndGenerateGraphics(null);

                                // Finish the sheet
                                pe.EndPage(null);
                                ppd.SheetProgressPos = 100;
                                ppd.PlotProgressPos = 100; //+= Convert.ToInt32(100 / BlocksToPlot.Count);
                                ppd.OnEndSheet();
                                // Finish the document and finish the plot
                                pe.EndDocument(null);

                                ppd.PlotProgressPos = 100;
                                ppd.OnEndPlot();
                                pe.EndPlot(null);
                                ed.WriteMessage("\nPlot completed successfully!\n\n");
                                ps.Dispose();
                                pe.Dispose();
                                ppd.Dispose();
                            }
                        }
                        //Task.Delay(2000);

                        //doc.CloseAndDiscard();

                        // 关闭绘图过程
                        //PlotFactory.ProcessPlotState = PlotState.Cancel;
                    }
                    else
                    {
                        ed.WriteMessage("\nAnother plot is in progress.\n\n");
                    }
                    tr.Commit();
                    tr.Dispose();
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.PlotSettings): DisposableWrapper
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.ViewTableRecord): DisposableWrapper

                }
                //Application.SetSystemVariable("BACKGROUNDPLOT", SysVarBackPlot);
                //if (this.pdfform != null)
                //{
                //    this.pdfform.Close();
                //    this.pdfform = null;

                //}
                //pdfform = new PdfProgressForm(selectedProductCode, new Action<int>((r) =>
                //{
                //    if (r == 1)
                //    {
                //        //uploadPdf();
                //        //this.pdfform.Close();
                //    }
                //    else
                //    {
                //        //ed.WriteMessage("\n上传pdf失败");
                //    }
                //}));
                //// 显示 Windows Form 窗口
                //Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, pdfform);
                //pdfform.beginProcess();

                //for (int i = 0; i <= 100; i++)
                //{
                //    SimpleProgressBar bar = new SimpleProgressBar();
                //    bar.Show();
                //    bar.UpdateProgress(100);

                //    //Thread.Sleep(100); // 模拟任务的执行时间
                //    Task.Delay(TimeSpan.FromSeconds(2)).Wait(); //等待2秒
                //    String filePath = GValues.pdfPath + "\\selectDWGWindow.pdf";
                //    // 判断文件是否存在
                //    if (File.Exists(filePath))
                //    {
                //        bar.Close();
                //        DialogResult res = MessageBox.Show("PDF文件已经生成，确认要上传吗？", "上传提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                //        if (res == DialogResult.OK)  //1为确定，2为取消,...
                //        {
                //            //按OK后，执行语句；
                //            if (checkProductCode)
                //            {
                //                uploadPdf();
                //            }
                //        }
                //        if (res == DialogResult.Cancel)  //1为确定，2为取消,...
                //        {
                //            //按Cancel后，执行语句；
                //        }

                //        break;
                //        //Thread.Sleep(2000);
                //        //uploadPdf();
                //        //ed.WriteMessage("上传完成！");
                //    }
                // }

            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {

            }
            finally
            {

            }

            //RotateAndReplaceImage(OutPath+".png",filename);
            ConvertPdfToPngWithDpi(OutPath, GValues.pdfPath +"\\png\\",filename);

        }
        public void ConvertPdfToPngWithDpi(string pdfPath, string outputFolder,string filename, int dpi = 300)
        {
            if (pdfPath == "")
            {
                MessageBox.Show("没选择数据！");
            }
            using (var document = PdfDocument.Load(pdfPath))
            {
                for (int i = 0; i < document.PageCount; i++)
                {
                    // 设置渲染尺寸和DPI以提高清晰度
                    Size size = new Size(
                        (int)document.PageSizes[i].Width * 10, 
                        (int)document.PageSizes[i].Height * 10
                    );

                    using (var image = document.Render(i,  (int)(dpi * 1.5), (int)(dpi * 1.5), dpi, dpi, false))
                    {
                        string outputPath = Path.Combine(outputFolder, filename+ ".png");
                        image.Save(outputPath, ImageFormat.Png);
                    }
                }
            }
            if (File.Exists(GValues.pdfPath + "\\" + filename + ".png"))
            {
                try
                {
                    // 尝试删除文件
                    File.Delete(GValues.pdfPath + "\\" + filename + ".png");
                }
                catch (IOException ex)
                {                    // IO异常处理

                }
            }
            try
            {
                File.Delete(pdfPath);
                File.Move(outputFolder + filename + ".png", GValues.pdfPath + "\\" + filename + ".png");
            }
            catch (IOException ex)
            {

            }
        }

        public void RotateAndReplaceImage(string filePath,string filename)
        {
            string tempFile = Path.GetTempFileName();

            using (Bitmap originalImage = new Bitmap(filePath))
            {
                originalImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
                originalImage.Save(tempFile, ImageFormat.Png);
            }
            if (File.Exists(GValues.pdfPath + "\\" + filename + ".png"))
            {
                try
                {
                    // 尝试删除文件
                    File.Delete(GValues.pdfPath + "\\" + filename + ".png");
                }
                catch (IOException ex)
                {                    // IO异常处理

                }
            }
            try
            {
                File.Delete(filePath);
                File.Move(tempFile, GValues.pdfPath + "\\" + filename + ".png");
            }
            catch (IOException ex)
            {

            }
        }

        public void PlotBlockColToPDF()
        {
            InitDomainConfig();
            getUserInfo();
            String OutPath = "";
            String processHandleId = "";
            Boolean checkProductCode = false;
            Directory.CreateDirectory(GValues.pdfPath);
            Dictionary<String, Dictionary<String, String>> tableDict = new Dictionary<string, Dictionary<string, string>>();
            SetObject setObject = new SetObject();
            setObject.initTableDictData(tableDict);
            // 判断文件是否存在
            //if (File.Exists(OutPath))
            //{
            //    try
            //    {
            //        // 尝试删除文件
            //        File.Delete(OutPath);
            //        outMsg.AddMsg("文件已删除。");
            //    }
            //    catch (IOException ex)
            //    {                    // IO异常处理
            //        outMsg.AddMsg("无法删除文件: " + ex.Message);
            //    }
            //}
            try
            {

                String BlockName;
                String PrinterName = "DWG To PDF.pc3";

                String PaperSize = "ISO_full_bleed_A4_(210.00_x_297.00_MM)";//"ISO_A4_(210.00_x_297.00_MM)";
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                ppo.AllowNone = false;
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d first1 = ppr.Value;
                PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", first1);
                ppr = ed.GetCorner(pco);
                if (ppr.Status != PromptStatus.OK)
                    return;
                Point3d second2 = ppr.Value;

                ///wcs 2 ucs
                ///
                //Vector3d vect = db.Ucsorg.GetVectorTo(new Point3d(0,0,0));
                //Matrix3d matWCS2UCS = Matrix3d.WorldToPlane(vect);
                //Point3d second = second1.TransformBy(matWCS2UCS);
                //Point3d first = first1.TransformBy(matWCS2UCS);
                ////


                //Matrix3d wcs2ucs = doc.Editor.CurrentUserCoordinateSystem.Inverse();
                //Point3d ucsPoint = worldPoint.TransformBy(wcs2ucs);

                //wcs 2 dcs
                //
                //
                // Gets the current view
                //ViewTableRecord acView = doc.Editor.GetCurrentView();
                ////Extents3d eExtents = new Extents3d(new Point3d(0, 0, 0), new Point3d(630, 445.5, 0));
                //Extents3d eExtents = new Extents3d(first, second);
                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                               acView.ViewDirection,
                //                               acView.Target) * matWCS2DCS;

                //// Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);

                //
                //ViewTableRecord acView = doc.Editor.GetCurrentView();

                //Extents3d eExtents = new Extents3d(first, second);

                //// Translates WCS coordinates to DCS
                //Matrix3d matWCS2DCS;
                //matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                //matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                //matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                //                                acView.ViewDirection,
                //                                acView.Target) * matWCS2DCS;

                ////Tranforms the extents to DCS
                //matWCS2DCS = matWCS2DCS.Inverse();
                //eExtents.TransformBy(matWCS2DCS);
                //var wcsWindow = new Extents2d(eExtents.MinPoint.X, eExtents.MinPoint.Y,
                //                                        eExtents.MaxPoint.X, eExtents.MaxPoint.Y);

                //
                // 获取当前视图方向
                Vector3d viewDir = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;

                // 获取当前视图位置
                Point3d viewPos = ed.GetCurrentView().Target;

                // 构造视图变换矩阵
                Matrix3d viewTransform = Matrix3d.WorldToPlane(viewDir).Inverse();
                //viewTransform = Matrix3d.Displacement(viewPos.GetAsVector()) * viewTransform;

                //// 将WCS坐标转换为DCS坐标
                Point3d first = first1.TransformBy(viewTransform);
                Point3d second = second2.TransformBy(viewTransform);


                ///====

                // Transform from UCS to DCS
                ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                double[] firres = new double[] { 0, 0, 0 };
                double[] secres = new double[] { 0, 0, 0 };
                // Transform the first point...
                acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                // ... and the second
                acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                // We can safely drop the Z-coord at this stage
                Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                //Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT");
                //Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    // We'll be plotting the current layout
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);

                    // 定义过滤条件，设置仅选择BlockReference

                    //SelectionFilter filter = new SelectionFilter(new TypedValue[]
                    //{
                    //    new TypedValue((int)DxfCode.Start, "TEXT") // "INSERT"代表图块引用
                    //});
                    // 使用选取窗口和过滤条件进行选择
                    PromptSelectionResult selectionResult = ed.SelectCrossingWindow(first, second);

                    // 检查选择结果
                    if (selectionResult.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\n未选择对象或操作取消。");
                        return;
                    }
                    //Dictionary<String, String> fieldDict = new Dictionary<string, string>();
                    selectedProcessName = "";
                    SelectionSet sSet = selectionResult.Value;
                    ObjectId[] selectedIds = sSet.GetObjectIds();  // 获取选择对象的ObjectiID数组.
                    foreach (ObjectId objId in selectedIds)
                    {
                        Entity entity = tr.GetObject(objId, OpenMode.ForRead) as Entity;
                        if (entity is Table)
                        {
                           
                            Table table = entity as Table;
                            // 你现在可以使用table对象了
                            // ...
                            processHandleId = table.Handle.Value.ToString();
                            if (table.XData != null)
                            {
                                Dictionary<String, String> xDataDict = new Dictionary<string, string>();
                                String tableType = "none";
                                ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                // 遍历ResultBuffer以查看数据
                                foreach (TypedValue tv in rb)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            var a = tv.Value.ToString();
                                            ed.WriteMessage("\n APP Code :" + a);
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            var b = tv.Value.ToString();
                                            if (b.IndexOf("tableType:") != -1)
                                            {
                                                String[] cc = b.Split(':');
                                                if (cc[1] == "processSop")
                                                {
                                                    tableType = "processSop";
                                                    xDataDict["processSop"] = "true"; //SOP图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "processBom")
                                                {
                                                    tableType = "processBom";
                                                    xDataDict["processBom"] = "true"; //工艺图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                                if (cc[1] == "productBom")
                                                {
                                                    tableType = "productBom";
                                                    xDataDict["productBom"] = "true"; //产品图纸表格
                                                    xDataDict["tableHandleId"] = processHandleId;
                                                }
                                            } else if  (b.IndexOf("processName:") != -1) {
                                                ed.WriteMessage("\n Process Name :" + b);
                                                String[] cc = b.Split(':');
                                                selectedProcessName = cc[1];
                                                xDataDict["processName"] = cc[1];
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }
                                            else if (b.IndexOf("productCode:") != -1)
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                String[] cc = b.Split(':');
                                                selectedProductCode = cc[1];
                                                xDataDict["productCode"] = cc[1];
                                                checkProductCode = true;
                                            } else 
                                            {
                                                ed.WriteMessage("\n Product Code :" + b);
                                                selectedProductCode = b;
                                                checkProductCode = true;
                                                xDataDict["productCode"] = b;
                                                xDataDict["oldTable"] = "true";
                                                tableType = "oldTable";
                                                xDataDict["tableHandleId"] = processHandleId;
                                            }                                            
                                            break;
                                        // 其他类型的DXF组码...

                                    }
                                }
                                tableDict[tableType] = xDataDict;
                            }
                            else
                            {
                                ed.WriteMessage("\n实体没有扩展数据！");
                            }
                        }

                    }
                    if (!checkProductCode)
                    {
                        ed.WriteMessage("\n选择框内没有定义工艺数据！");
                        return;
                    }
                    else
                    {
                        if (tableDict["productBom"]["productBom"] == "true" && tableDict["processBom"]["processBom"] == "false" && tableDict["processSop"]["processSop"] == "false")
                        {
                            ed.WriteMessage("\n选择框内没有定义工艺数据！");
                            return;
                        }
                    }
                    Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);
                    
                    if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                    {
                        PlotEngine pe = PlotFactory.CreatePublishEngine();
                        using (pe)
                        {
                            PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true);
                            using (ppd)
                            {
                                int numSheet = 1;
                                // Setting up the PlotProgress dialog
                                ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                                ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                ppd.LowerPlotProgressRange = 0;
                                ppd.UpperPlotProgressRange = 100;
                                ppd.PlotProgressPos = 0;


                                ppd.OnBeginPlot();
                                ppd.IsVisible = true;
                                pe.BeginPlot(ppd, null);

                                ppd.StatusMsgString = "Plotting block 1";
                                ppd.OnBeginSheet(); //????
                                ppd.LowerSheetProgressRange = 0;
                                ppd.UpperSheetProgressRange = 100;
                                ppd.SheetProgressPos = 0;

                                PlotInfoValidator piv = new PlotInfoValidator();
                                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                PlotPageInfo ppi = new PlotPageInfo();
                                PlotInfo pi = new PlotInfo();
                                //BlockReference blk = gblk.BlockRef;
                                //Layout lo = btr.LayoutObj;

                                //// Getting coodinates of window to plot
                                //Extents3d ext = (Extents3d)blk.Bounds;
                                //Point3d first = ext.MaxPoint;
                                //Point3d second = ext.MinPoint;
                                //ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                                //double[] firres = new double[] { 0, 0, 0 };
                                //double[] secres = new double[] { 0, 0, 0 };
                                //acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                                //acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                                //Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                                // We need a PlotSettings object based on the layout settings which we then customize
                                PlotSettings ps = new PlotSettings(lo.ModelType);
                                //ps.PlotPlotStyles = true;
                                // Specify the plot options

                                LayoutManager.Current.CurrentLayout = lo.LayoutName;
                                pi.Layout = lo.Id;
                                ps.CopyFrom(lo);
                                ps.PrintLineweights = true;
                                ps.PlotTransparency = false;
                                ps.PlotPlotStyles = true;
                                ps.DrawViewportsFirst = true;
                                ps.ShowPlotStyles = true;
                                //PlotStyleTable = GetVauleFromArray("CtbThinnerLinesName")
                                // The PlotSettingsValidator helps create a valid PlotSettings object
                                PlotSettingsValidator psv = PlotSettingsValidator.Current;
                                psv.SetPlotConfigurationName(ps, PrinterName, PaperSize);
                                psv.RefreshLists(ps);
                                psv.SetPlotWindowArea(ps, window);
                                psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                                psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                                psv.SetCurrentStyleSheet(ps, "monochrome.ctb");
                                ////
                                //var e = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("PSTYLEMODE");
                                //var a = db.PlotStyleMode;
                                //var b = psv.GetPlotStyleSheetList();
                                //foreach (String CTB in b)
                                //{
                                //    var c = CTB;
                                //}
                                //if (a)
                                //{
                                //     psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

                                //}
                                //else
                                //{
                                //    psv.SetCurrentStyleSheet(ps, "monochrome.stb");
                                //}

                                
                                psv.SetPlotCentered(ps, true);                               

                                pi.OverrideSettings = ps;
                                piv.Validate(pi);
                                if (selectedProcessName != "")
                                {
                                    OutPath = GValues.pdfPath + "\\" + selectedProductCode + "-process-" + selectedProcessName + "-" + tableDict["processSop"]["tableHandleId"] + ".pdf";
                                }
                                else
                                {
                                    OutPath = GValues.pdfPath + "\\" + selectedProductCode + ".pdf";
                                }
                                
                                pe.BeginDocument(pi, doc.Name, null, 1, true, OutPath); // Create document for the first page

                                // Plot the window
                                pe.BeginPage(ppi, pi, true, null);
                                pe.BeginGenerateGraphics(null);
                                ppd.SheetProgressPos = 50;
                                pe.EndGenerateGraphics(null);

                                // Finish the sheet
                                pe.EndPage(null);
                                ppd.SheetProgressPos = 100;
                                ppd.PlotProgressPos = 100; //+= Convert.ToInt32(100 / BlocksToPlot.Count);
                                ppd.OnEndSheet();
                                // Finish the document and finish the plot
                                pe.EndDocument(null);

                                ppd.PlotProgressPos = 100;
                                ppd.OnEndPlot();
                                pe.EndPlot(null);
                                ed.WriteMessage("\nPlot completed successfully!\n\n");
                                ps.Dispose();
                                pe.Dispose();
                                ppd.Dispose();
                            }
                        }
                        //Task.Delay(2000);

                        //doc.CloseAndDiscard();

                        // 关闭绘图过程
                        //PlotFactory.ProcessPlotState = PlotState.Cancel;
                    }
                    else
                    {
                        ed.WriteMessage("\nAnother plot is in progress.\n\n");
                    }
                    tr.Commit();
                    tr.Dispose();
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.PlotSettings): DisposableWrapper
                    //Forgot to call Dispose? (Autodesk.AutoCAD.DatabaseServices.ViewTableRecord): DisposableWrapper

                }
                //Application.SetSystemVariable("BACKGROUNDPLOT", SysVarBackPlot);
                //if (this.pdfform != null)
                //{
                //    this.pdfform.Close();
                //    this.pdfform = null;

                //}
                //pdfform = new PdfProgressForm(selectedProductCode, new Action<int>((r) =>
                //{
                //    if (r == 1)
                //    {
                //        //uploadPdf();
                //        //this.pdfform.Close();
                //    }
                //    else
                //    {
                //        //ed.WriteMessage("\n上传pdf失败");
                //    }
                //}));
                //// 显示 Windows Form 窗口
                //Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, pdfform);
                //pdfform.beginProcess();

                //for (int i = 0; i <= 100; i++)
                //{
                //    SimpleProgressBar bar = new SimpleProgressBar();
                //    bar.Show();
                //    bar.UpdateProgress(100);

                //    //Thread.Sleep(100); // 模拟任务的执行时间
                //    Task.Delay(TimeSpan.FromSeconds(2)).Wait(); //等待2秒
                //    String filePath = GValues.pdfPath + "\\selectDWGWindow.pdf";
                //    // 判断文件是否存在
                //    if (File.Exists(filePath))
                //    {
                //        bar.Close();
                //        DialogResult res = MessageBox.Show("PDF文件已经生成，确认要上传吗？", "上传提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                //        if (res == DialogResult.OK)  //1为确定，2为取消,...
                //        {
                //            //按OK后，执行语句；
                //            if (checkProductCode)
                //            {
                //                uploadPdf();
                //            }
                //        }
                //        if (res == DialogResult.Cancel)  //1为确定，2为取消,...
                //        {
                //            //按Cancel后，执行语句；
                //        }

                //        break;
                //        //Thread.Sleep(2000);
                //        //uploadPdf();
                //        //ed.WriteMessage("上传完成！");
                //    }
                // }

            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {

            }
            finally
            {

            }



        }

        public  void uploadPdf()
        {
            try
            {
                Http.CreateHttpClient(GValues.domainLink + "sys/common/upload?biz=" + "drawing/" + GValues.tenant + "/plot", GValues.tenant, GValues.token).UploadFileAsync(GValues.pdfPath + "\\selectDWGWindow.pdf", new Action<Http.HttpResp>((r1) =>
                {
                    var responCode = Convert.ToInt32(r1.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<String> cc = JsonConvert.DeserializeObject<ResponResult<String>>(r1.AckStr());
                        BasProduct basProduct = new BasProduct();
                        basProduct.attachment = cc.message;
                        basProduct.code = selectedProductCode;
                        saveProductAttachemt(basProduct);
                    }
                    else
                    {
                        this.outMsg.AddMsg("上传图纸报错！" + r1.Code + " " + " " + responCode + " " + r1.Error);
                    }
                }));
            }
            catch (System.Exception e)
            {
                this.outMsg.AddMsg("上传图纸报错！" + e.Message);
            } 
        }

        public void saveProductAttachemt(BasProduct basProduct)
        {
            try
            {
                string postData = JsonConvert.SerializeObject(basProduct);
                Http.CreateHttpClient(GValues.domainLink + "bas/basProduct/cad-edit", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        this.outMsg.AddMsg("上传图纸成功！");
                    }
                    else
                    {
                        this.outMsg.AddMsg("上传附件数据失败！" + r.Code + " " + " " + responCode + " " + r.Error);
                    }
                }));
            }
            catch (System.Exception e)
            {
                this.outMsg.AddMsg("上传附件报错！" + e.Message);
            }
        }
        #endregion

        [CommandMethod("TT2")]
        public void ModifySelectionTable()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            string productCode = "";
            bool isProcessBom = true;
            string domainid = "";
            GValues.clickButtonText = "修改";
            PromptSelectionOptions options = new PromptSelectionOptions();
            options.MessageForAdding = "选择表格对象";            
            PromptSelectionResult result = ed.GetSelection(options);

            
            if (result.Status == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    SelectionSet ss = result.Value;
                    foreach (ObjectId id in ss.GetObjectIds())
                    {
                        Entity entity = tr.GetObject(id, OpenMode.ForRead) as Entity;
                        if (entity is Table)
                        {
                            Table table = entity as Table;
                            
                            // 你现在可以使用table对象了
                            // ...
                            if (table.XData != null)
                            {
                                ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                // 遍历ResultBuffer以查看数据
                                foreach (TypedValue tv in rb)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            domainid = tv.Value.ToString();
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            String data = tv.Value.ToString();
                                            if (data.IndexOf("productCode:") != -1) {
                                                productCode = data.Split(':')[1] ;
                                            }
                                            if (data.IndexOf("tableType:productBom") != -1)
                                            {
                                                isProcessBom = false;
                                            }
                                            if (data.IndexOf(":") == -1) //已经存在的表格
                                            {
                                                productCode = tv.Value.ToString();
                                            }
                                            break;
                                        // 其他类型的DXF组码...
                                    }
                                }
                            }
                            else
                            {
                                ed.WriteMessage("\n实体没有扩展数据！");
                            }
                        }
                    }
                    tr.Commit();
                }
            }
            if (productCode != "" && isProcessBom)
            {
                GValues.productCode = productCode;
                this.ModifyBomCommand();

            }
            else
            {
                ed.WriteMessage("\n选择的不是工艺BOM表格！");
            }
        }
        private void BomForm_Disposed(object sender, EventArgs e) {
            MessageBox.Show("Bom form 资源释放了！");

        }
        
        private void ModifyBomCommand()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor editor = doc.Editor;
            if (bomForm == null)
            {
                // 创建 Windows Form 窗口
                bomForm = new BomForm();
                bomForm.FormClosed += BomForm_FormClosed;
            }
            InitTableEvent();
            InitDomainConfig();
            getUserInfo();

            // 显示 Windows Form 窗口
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, bomForm);
            //bomForm.WindowState = FormWindowState.Normal;
            bomForm.initBomFromData();

        }

         [CommandMethod("GetInBlockTable")]
        public void GetBlockXData()
{
    Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
    Database db = doc.Database;
    Editor ed = doc.Editor;

    using (Transaction tr = db.TransactionManager.StartTransaction())
    {
        try
        {
            // 选择块参照
            PromptEntityOptions opts = new PromptEntityOptions("\n选择块参照: ");
            opts.SetRejectMessage("\n必须选择块参照");
            opts.AddAllowedClass(typeof(BlockReference), false);
            
            PromptEntityResult res = ed.GetEntity(opts);
            if (res.Status != PromptStatus.OK) return;

            BlockReference br = tr.GetObject(res.ObjectId, OpenMode.ForRead) as BlockReference;
            
            // 获取块定义
            BlockTableRecord btr = tr.GetObject(br.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
            
            // 遍历块内实体
            foreach (ObjectId entId in btr)
            {
                Entity ent = tr.GetObject(entId, OpenMode.ForRead) as Entity;
                
                            // 修正为检测真正的 Table 对象
                if (ent is Table) 
                {
                    Table table = ent as Table;
                    ResultBuffer xdata = table.XData;
        
                    if (xdata != null)
                    {
                        TypedValue[] values = xdata.AsArray();
                        ed.WriteMessage("\n找到表格对象（行数：{table.Rows.Count}，列数：{table.Columns.Count}）");
                        // 处理表格的XData...
                    }
                }
            }
            tr.Commit();
        }
        catch (Autodesk.AutoCAD.Runtime.Exception ex)
        {
            ed.WriteMessage("\n错误: {}" + ex.Message);
        }
    }
}

         [CommandMethod("WW99")]
         public void ModifyBomTable()
         {
             Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
             Database db = doc.Database;
             Editor ed = doc.Editor;
             GValues.clickButtonText = "修改";
             string domainid = "";
             string productCode = "";
             // 选择表格对象
             PromptEntityOptions opts = new PromptEntityOptions("\nSelect a table: ");
             opts.SetRejectMessage("\nSelected object is not a table.");
             opts.AddAllowedClass(typeof(Table), true);
             PromptEntityResult tableResult = ed.GetEntity(opts);

             if (tableResult.Status == PromptStatus.OK)
             {
                 using (Transaction tr = db.TransactionManager.StartTransaction())
                 {
                     Table table = tr.GetObject(tableResult.ObjectId, OpenMode.ForWrite) as Table;

                     //// 修改表格数据
                     //table.Cells[1, 1].TextString = "New Value"; // 修改第一行第一列的数据

                     //// 添加新行数据
                     //int newRow = table.Rows.Count - 1; // 添加到倒数第二行，最后一行为标题行
                     //table.InsertRows(newRow, table.Rows[1].Height, 1); // 在指定位置插入新行
                     //table.Cells[newRow, 0].TextString = "New Row Data 1"; // 设置新行第一列数据
                     //table.Cells[newRow, 1].TextString = "New Row Data 2"; // 设置新行第二列数据

                     //ResultBuffer rb = new ResultBuffer();
                     //rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"));
                     //rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "作者：John Doe"));
                     //table.XData = rb;
                     // 检查实体是否存在扩展数据
                     if (table.XData != null)
                     {
                         ResultBuffer rb = table.XData; // 获取实体的扩展数据

                         // 遍历ResultBuffer以查看数据
                         foreach (TypedValue tv in rb)
                         {
                             switch ((DxfCode)tv.TypeCode)
                             {
                                 case DxfCode.ExtendedDataRegAppName:
                                     domainid = tv.Value.ToString();
                                     break;
                                 case DxfCode.ExtendedDataAsciiString:
                                     productCode = tv.Value.ToString();
                                     break;
                                 // 其他类型的DXF组码...
                             }
                         }
                     }
                     else
                     {
                         ed.WriteMessage("\n实体没有扩展数据！");
                     }
                     tr.Commit();

                 }
             }
             if (productCode != "")
             {
                 GValues.productCode = productCode;
                 this.ModifyBomCommand();
             }
         }
        #endregion

         #region 命令测试代码块

         [CommandMethod("GetSelectionTable")]
         public void GetSelectionTable()
         {
             Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
             Database db = doc.Database;
             Editor ed = doc.Editor;

             PromptSelectionOptions options = new PromptSelectionOptions();
             options.MessageForAdding = "选择对象";
             PromptSelectionResult result = ed.GetSelection(options);

             if (result.Status == PromptStatus.OK)
             {
                 using (Transaction tr = db.TransactionManager.StartTransaction())
                 {
                     SelectionSet ss = result.Value;
                     foreach (ObjectId id in ss.GetObjectIds())
                     {
                         Entity entity = tr.GetObject(id, OpenMode.ForRead) as Entity;
                         
                         if (entity is Table)
                         {
                             Table table = entity as Table;
                             // 你现在可以使用table对象了
                             // ...
                         }
                     }
                     tr.Commit();
                 }
             }
         }

         [CommandMethod("InsertTable")]
         public void InsertTable()
         {
             Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
             Editor ed = doc.Editor;

             // 获取点
             PromptPointOptions pointOptions = new PromptPointOptions("\n点击位置插入表格");
             PromptPointResult pointResult = ed.GetPoint(pointOptions);
             if (pointResult.Status != PromptStatus.OK)
                 return;

             // 插入表格
             using (Transaction tr = doc.TransactionManager.StartTransaction())
             {
                 BlockTable bt = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                 BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                 Table table = new Table();
                 table.SetSize(5, 3); // 行数和列数
                 table.Position = pointResult.Value;

                 btr.AppendEntity(table);
                 tr.AddNewlyCreatedDBObject(table, true);

                 tr.Commit();
             }

             ed.Regen();
         }

         [CommandMethod("InsertTableWithXData")]
         public void InsertTableWithXData()
         {
             Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
             Database db = doc.Database;
             Editor ed = doc.Editor;
             // 获取当前绘图区域的中心点
             Point3d insPoint = doc.Editor.GetPoint("\n选择表格插入点: ").Value;

             using (Transaction tr = db.TransactionManager.StartTransaction())
             {
                 // 创建一个新的表格对象
                 Table table = new Table();
                 table.SetSize(3, 3);
                 //table.Position = new Point3d(0, 0, 0);
                 table.Position = insPoint;
                 // 将表格对象添加到数据库中
                 BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                 BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                 btr.AppendEntity(table);
                 tr.AddNewlyCreatedDBObject(table, true);

                 // 为表格对象添加XData
                 ResultBuffer rb = new ResultBuffer(
                     new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"),
                     new TypedValue((int)DxfCode.ExtendedDataAsciiString, "CustomData:1304-000462-00"),
                     new TypedValue((int)DxfCode.ExtendedDataLayerName, "ProcessName:下料"),
                     new TypedValue((int)DxfCode.ExtendedDataAsciiString, "CustomData:1988")
                 );

                 table.XData = rb;

                 tr.Commit();
             }

             ed.WriteMessage("Table inserted with XData successfully.");
         }
          

         public void FOB2DATA()
         {
             //List<String> itemList = new List<string> { "项1", "项2", "项3" };
             if (setProcessNameForm == null)
             {
                 setProcessNameForm = new SetProcessName();
                 setProcessNameForm.FormClosed += setProcessNameForm_FormClosed;
             }
             // 显示 Windows Form 窗口
             Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, setProcessNameForm);
             setProcessNameForm.initData(new Action<String>((res)=>{
                 getProcessView(res);
             }),itemList);
         }
        [CommandMethod("SOP2")]
        public void FOB2GETPROCESSNAME(){
            //获取用户登入信息
            InitDomainConfig();
            getUserInfo();
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            itemList = new List<string>();
            // 选择表格对象
            PromptEntityOptions opts = new PromptEntityOptions("\n选择表格: ");
            opts.SetRejectMessage("\n没选择正确的表格对象.");
            opts.AddAllowedClass(typeof(Table), true);
            PromptEntityResult tableResult = ed.GetEntity(opts);
            bool isSopProcessBom = false;
            if (tableResult.Status == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    Table table = tr.GetObject(tableResult.ObjectId, OpenMode.ForWrite) as Table;
                    handleId = table.Handle.Value;
                    for (int i = 2; i < table.Rows.Count; i++)
                    {
                        itemList.Add(table.Cells[i, 1].TextString.Replace("*", ""));
                    }

                    if (table.XData != null)
                    {
                        rbXdata = table.XData;
                        ResultBuffer rb = table.XData; // 获取实体的扩展数据

                        // 遍历ResultBuffer以查看数据
                        foreach (TypedValue tv in rb)
                        {
                            switch ((DxfCode)tv.TypeCode)
                            {
                                case DxfCode.ExtendedDataRegAppName:
                                    //domainid = tv.Value.ToString();
                                    break;
                                case DxfCode.ExtendedDataAsciiString:
                                    String data = tv.Value.ToString();
                                    if (data.IndexOf("productCode:") != -1)
                                    {
                                        //productCode = data.Split(':')[1];
                                    }
                                    if (data.IndexOf("tableType:productBom") != -1)
                                    {
                                        isSopProcessBom = true;
                                    }
                                    break;
                                // 其他类型的DXF组码...
                            }
                        }
                    }
                    tr.Commit();
                }
            }
            //if (!isSopProcessBom)
            //{
            //    ed.WriteMessage("\n选择的不是SOP表格！");
            //    return;
            //}
            if (itemList != null && itemList.Count > 0)
            {
                FOB2DATA();
            }
        }
        private void getProcessView(String processName)
        {
            setProcessNameForm.Close();
            setProcessNameForm = null;

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            //获取到了token
            Http.CreateHttpClient(GValues.tenant, GValues.token).GetAsync(GValues.domainLink + "bas/basProcess/list?pageSize=100000", new Action<Http.HttpResp>((r2) =>
            {
                var responCode = Convert.ToInt32(r2.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultA<BasProcess> cc = JsonConvert.DeserializeObject<ResponResultA<BasProcess>>(r2.AckStr());
                    if (cc.success)
                    {
                        basProcessList = cc.result.records;

                        BasProcess basProcess = basProcessList.ToList().Find(p => p.name == processName);
                        FOB2TABLE(processName,basProcess.id);
                    }
                    else
                    {
                       ed.WriteMessage(cc.message);
                    }
                }
                else
                {
                    ed.WriteMessage(r2.Error);
                }
            }));

        }

        public void FOB2TABLE(String processName,String processId)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();

            // 选择表格对象
            //PromptEntityOptions opts = new PromptEntityOptions("\n选择表格: ");
            //opts.SetRejectMessage("\n选择的不是表格对象.");
            //opts.AddAllowedClass(typeof(Table), true);
            //PromptEntityResult tableResult = ed.GetEntity(opts);

            if (PromptStatus.OK == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    //Table table = tr.GetObject(tableResult.ObjectId, OpenMode.ForWrite) as Table;
                    ObjectId objectid = db.GetObjectId(false, new Handle(handleId), 0);
                    ObjectId[] ids = new ObjectId[] { objectid };
                    if (ids.Length > 0)
                    {
                        foreach (ObjectId id in ids)
                        {
                             Entity ent = id.GetObject(OpenMode.ForWrite) as Entity;
                                //Entity ent1 = tr.GetObject(id, OpenMode.ForRead) as Entity; 另外一种获取表格的方法
                             if (ent is Table)
                             {
                                 Table table = ent as Table;
                                 //解锁
                                 for (int row = 0; row < (table.Rows.Count - 2); row++)
                                 {
                                     table.Cells[row + 2, 0].State = CellStates.None;
                                     table.Cells[row + 2, 1].State = CellStates.None;
                                     table.Cells[row + 2, 2].State = CellStates.None;
                                     table.Cells[row + 2, 3].State = CellStates.None;
                                     table.Cells[row + 2, 4].State = CellStates.None;
                                 }

                                 for (int i = 2; i < table.Rows.Count; i++)
                                 {
                                     table.Cells[i, 1].TextString = table.Cells[i, 1].TextString.Replace("*", "");
                                     if (table.Cells[i, 1].TextString == processName)
                                     {
                                         table.Cells[i, 1].TextString = table.Cells[i, 1].TextString + "*";
                                     }
                                 }
                                 //上锁
                                 for (int row = 0; row < (table.Rows.Count - 2); row++)
                                 {
                                     table.Cells[row + 2, 0].State = CellStates.ContentLocked;
                                     table.Cells[row + 2, 1].State = CellStates.ContentLocked;
                                     table.Cells[row + 2, 2].State = CellStates.ContentLocked;
                                     table.Cells[row + 2, 3].State = CellStates.ContentLocked;
                                     table.Cells[row + 2, 4].State = CellStates.ContentLocked;
                                 }
                                 table.GenerateLayout();
                                 ResultBuffer rb = new ResultBuffer(); ;
                                 rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"));
                                 String XData_productCode = "";
                                 foreach (TypedValue tv in rbXdata)
                                 {
                                     switch ((DxfCode)tv.TypeCode)
                                     {
                                         case DxfCode.ExtendedDataRegAppName:
                                             //rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, tv.ToString()));
                                             break;
                                         case DxfCode.ExtendedDataAsciiString:
                                             var b = tv.Value.ToString();
                                             if (b.IndexOf("processName:") != -1)
                                             {
                                                 
                                             }
                                             else if (b.IndexOf("productCode:") != -1)
                                             {
                                                 String[] cc = b.Split(':');
                                                 XData_productCode = cc[1];
                                             }
                                             else if (b.IndexOf("tableType:") != -1)
                                             {

                                             } else {
                                                 XData_productCode = tv.Value.ToString();
                                             }
                                             
                                             break;
                                         // 其他类型的DXF组码...
                                     }
                                 }
                                 rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "productCode:" + XData_productCode));
                                 rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString,"processName:"+ processId));
                                 rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "tableType:processSop"));
                                 
                                 table.XData = rb;
                             }
                        }
                    }
                    
                    // 检查实体是否存在扩展数据
                    //if (table.XData != null)
                    //{
                    //    ResultBuffer rb = table.XData; // 获取实体的扩展数据

                    //    // 遍历ResultBuffer以查看数据
                    //    foreach (TypedValue tv in rb)
                    //    {
                    //        switch ((DxfCode)tv.TypeCode)
                    //        {
                    //            case DxfCode.ExtendedDataRegAppName:
                    //                regAppName = tv.ToString();
                    //                break;
                    //            case DxfCode.ExtendedDataAsciiString:
                    //                asciiData = tv.ToString();
                    //                break;
                    //            case DxfCode.ExtendedDataLayerName:
                    //                controlData = tv.ToString();
                    //                break;
                    //            // 其他类型的DXF组码...
                    //        }
                    //    }
                    //}
                    //else
                    //{
                    //    ed.WriteMessage("\n实体没有扩展数据！");
                    //}
                    ed.WriteMessage("\n设定当前工艺成功。 ");
                    tr.Commit();
                    docLock.Dispose();
                    // 刷新并保存
                    doc.Editor.UpdateScreen();
                    doc.Editor.Regen();
                }
            }
        }

        [CommandMethod("RASTER_SAMPLE")]
        public static void RasterSampleCommand()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "JPeg Files|*.jpg|Gif Files|*.gif|PNG Files|*.png";
            ofd.FilterIndex = 0;
            ofd.Title = "Select Image File";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filename = ofd.FileName;
                using (Transaction trans = doc.TransactionManager.StartTransaction())
                {
                    ObjectId idModel = SymbolUtilityServices.GetBlockModelSpaceId(doc.Database);
                    BlockTableRecord ms = trans.GetObject(idModel, OpenMode.ForWrite) as BlockTableRecord;
                    RasterImageDef imageDef = AddImageDef(doc.Database, trans, filename);
                    if (imageDef != null)
                    {
                        RasterImage image = new RasterImage();
                        image.ImageDefId = imageDef.ObjectId;
                        ObjectId imageId = ms.AppendEntity(image);
                        if (imageId.IsNull)
                            throw new Autodesk.AutoCAD.Runtime.Exception(ErrorStatus.NullObjectId);
                        trans.AddNewlyCreatedDBObject(image, true);
                        RasterImage.EnableReactors(true);
                        image.AssociateRasterDef(imageDef);
                        Point3d origin = (Point3d)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("VIEWCTR");
                        image.Orientation = new CoordinateSystem3d(origin, Vector3d.XAxis, Vector3d.YAxis);
                        double scaleFactor = 10.0;
                        // 设置RasterImage的缩放值
                        double scaleX = 12.0; // X方向的缩放值
                        double scaleY = 12.0; // Y方向的缩放值
                        double scaleZ = 1.0; // Z方向的缩放值（通常为1）

                        // 创建一个缩放矩阵
                        Matrix3d scaleMatrix = Matrix3d.Scaling(scaleX, origin) * Matrix3d.Scaling(scaleY, origin) * Matrix3d.Scaling(scaleZ, origin);
                        // 应用缩放矩阵
                        image.TransformBy(scaleMatrix);
                        
                    }
                    trans.Commit();
                }
            }
        }

        public static RasterImageDef AddImageDef(Database db, Transaction trans, string imageFilespec)
        {
            if (!File.Exists(imageFilespec))
                throw new FileNotFoundException(imageFilespec);
            ObjectId idImageDict = RasterImageDef.GetImageDictionary(db);
            if (idImageDict.IsNull)
                idImageDict = RasterImageDef.CreateImageDictionary(db);
            if (idImageDict.IsNull)
                throw new InvalidOperationException("failed to get or create image dictionary");
            DBDictionary imageDictionary = trans.GetObject(idImageDict, OpenMode.ForRead) as DBDictionary;
            if (imageDictionary == null)
                throw new InvalidOperationException("Failed to open image dictionary");
            RasterImageDef imageDef = new RasterImageDef();
            try
            {
                imageDef.SourceFileName = imageFilespec;
                imageDef.Load();

                String name = RasterImageDef.SuggestName(imageDictionary, imageFilespec);

                imageDictionary.UpgradeOpen();
                ObjectId idEntry = imageDictionary.SetAt(name, imageDef);

                if (idEntry.IsNull)
                    throw new InvalidOperationException("Failed to add image definition to image dictionary");

                trans.AddNewlyCreatedDBObject(imageDef, true);

                return imageDef;

            }
            catch
            {
                imageDef.Dispose();
                throw;
            }

        }

        [CommandMethod("InsertQRCode")]
        public void InsertQRCode()
        {
            SetObject setObject = new SetObject();
            setObject.GenerateAndInsertQRCode("https://www.example.com", new Point3d(0, 0, 0), 1.0);
        }

        

         [CommandMethod("CheckXdata")]
         public void ModifyTable()
         {
             Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
             Database db = doc.Database;
             Editor ed = doc.Editor;
             string regAppName = "";
             string asciiData = "";
             string controlData = "";
             // 选择表格对象
             PromptEntityOptions opts = new PromptEntityOptions("\nSelect a table: ");
             opts.SetRejectMessage("\nSelected object is not a table.");
             opts.AddAllowedClass(typeof(Table), true);
             PromptEntityResult tableResult = ed.GetEntity(opts);

             if (tableResult.Status == PromptStatus.OK)
             {
                 using (Transaction tr = db.TransactionManager.StartTransaction())
                 {
                     Table table = tr.GetObject(tableResult.ObjectId, OpenMode.ForWrite) as Table;

                     // 修改表格数据
                     //table.Cells[1, 1].TextString = "New Value"; // 修改第一行第一列的数据

                     // 添加新行数据
                     //int newRow = table.Rows.Count - 1; // 添加到倒数第二行，最后一行为标题行
                     //table.InsertRows(newRow, table.Rows[1].Height, 1); // 在指定位置插入新行
                     //table.Cells[newRow, 0].TextString = "New Row Data 1"; // 设置新行第一列数据
                     //table.Cells[newRow, 1].TextString = "New Row Data 2"; // 设置新行第二列数据

                     //ResultBuffer rb = new ResultBuffer();
                     //rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"));
                     //rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "作者：John Doe"));
                     //table.XData = rb;
                     // 检查实体是否存在扩展数据
                     if (table.XData != null)
                     {
                         ResultBuffer rb = table.XData; // 获取实体的扩展数据

                         // 遍历ResultBuffer以查看数据
                         foreach (TypedValue tv in rb)
                         {
                             switch ((DxfCode)tv.TypeCode)
                             {
                                 case DxfCode.ExtendedDataRegAppName:
                                     regAppName = tv.ToString();
                                     ed.WriteMessage("\n找到的app字符串： " + regAppName);
                                     break;
                                 case DxfCode.ExtendedDataAsciiString:
                                     asciiData = tv.ToString();
                                     ed.WriteMessage("\n找到的ASCII字符串： " + asciiData);
                                     break;
                                 //case DxfCode.ExtendedDataLayerName:
                                 //    controlData = tv.ToString();
                                 //    break;
                                 // 其他类型的DXF组码...
                             }
                         }
                     }
                     else
                     {
                         ed.WriteMessage("\n实体没有扩展数据！");
                     }
                     //ed.WriteMessage("\n找到的CONTROL字符串： " + controlData);
                     //ed.WriteMessage("\n找到的ASCII字符串： " + asciiData);
                     //ed.WriteMessage("\n找到的app字符串： " + regAppName);
                     tr.Commit();

                 }
             }
         }
        //2025-3-26 提供导入工艺


         [CommandMethod("TT9")]
         public void BaigeBlockToPDFTT9()
         {
             InitDomainConfig();
             getUserInfo();
             Dictionary<String, String> result = new Dictionary<string, string>();
             String OutPath = "";
             String processHandleId = "";
             Boolean checkProductCode = false;
             Directory.CreateDirectory(GValues.pdfPath);
             Dictionary<String, Dictionary<String, String>> tableDict = new Dictionary<string, Dictionary<string, string>>();
             SetObject setObject = new SetObject();
             setObject.initTableDictData(tableDict);
             try
             {

                 String BlockName;
                 String PrinterName = "DWG To PDF.pc3";

                 String PaperSize = "ISO_full_bleed_A4_(210.00_x_297.00_MM)";//"ISO_A4_(210.00_x_297.00_MM)";
                 Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                 Editor ed = doc.Editor;
                 Database db = doc.Database;
                 Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);

                 PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                 ppo.AllowNone = false;
                 PromptPointResult ppr = ed.GetPoint(ppo);
                 if (ppr.Status != PromptStatus.OK)
                     return;
                 Point3d first1 = ppr.Value;
                 PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", first1);
                 ppr = ed.GetCorner(pco);
                 if (ppr.Status != PromptStatus.OK)
                     return;
                 Point3d second2 = ppr.Value;

                 //
                 // 获取当前视图方向
                 Vector3d viewDir = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;

                 // 获取当前视图位置
                 Point3d viewPos = ed.GetCurrentView().Target;

                 // 构造视图变换矩阵
                 Matrix3d viewTransform = Matrix3d.WorldToPlane(viewDir).Inverse();
                 //viewTransform = Matrix3d.Displacement(viewPos.GetAsVector()) * viewTransform;

                 //// 将WCS坐标转换为DCS坐标
                 Point3d first = first1.TransformBy(viewTransform);
                 Point3d second = second2.TransformBy(viewTransform);


                 ///====

                 // Transform from UCS to DCS
                 ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                 double[] firres = new double[] { 0, 0, 0 };
                 double[] secres = new double[] { 0, 0, 0 };
                 // Transform the first point...
                 acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                 // ... and the second
                 acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                 // We can safely drop the Z-coord at this stage
                 Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                 //Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT");
                 //Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                 Transaction tr = db.TransactionManager.StartTransaction();
                 using (tr)
                 {
                     // We'll be plotting the current layout
                     BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);

                     // 定义过滤条件，设置仅选择BlockReference

                     //SelectionFilter filter = new SelectionFilter(new TypedValue[]
                     //{
                     //    new TypedValue((int)DxfCode.Start, "TEXT") // "INSERT"代表图块引用
                     //});
                     // 使用选取窗口和过滤条件进行选择
                     PromptSelectionResult selectionResult = ed.SelectCrossingWindow(first, second);

                     // 检查选择结果
                     if (selectionResult.Status != PromptStatus.OK)
                     {
                         ed.WriteMessage("\n未选择对象或操作取消。");
                         return;
                     }
                     //Dictionary<String, String> fieldDict = new Dictionary<string, string>();
                     selectedProcessName = "";
                     SelectionSet sSet = selectionResult.Value;
                     ObjectId[] selectedIds = sSet.GetObjectIds();  // 获取选择对象的ObjectiID数组.
                     foreach (ObjectId objId in selectedIds)
                     {
                         Entity entity = tr.GetObject(objId, OpenMode.ForRead) as Entity;

                         if (entity is BlockReference)
                         {
                             BlockReference blockRef = entity as BlockReference;
                             // 获取块引用所在的图层
                             string layerName = blockRef.Layer;
                             // 获取块的名称
                             string blockName = blockRef.Name;
                             // 输出块引用的信息
                             ed.WriteMessage("\n在图层 {0} 找到块引用: {1}", layerName, blockName);

                             // 遍历块引用中的所有属性
                             foreach (ObjectId attId in blockRef.AttributeCollection)
                             {
                                 AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead);
                                 if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                                 {
                                     result["图号"] = attRef.TextString;
                                 }
                                 if (attRef.Tag.IndexOf("製程") != -1)
                                 {
                                     result[attRef.Tag] = attRef.TextString;
                                 }
                                 ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                             }
                         }

                         if (entity is Table)
                         {

                             Table table = entity as Table;
                             // 你现在可以使用table对象了
                             // ...
                             processHandleId = table.Handle.Value.ToString();
                             if (table.XData != null)
                             {
                                 Dictionary<String, String> xDataDict = new Dictionary<string, string>();
                                 String tableType = "none";
                                 ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                 // 遍历ResultBuffer以查看数据
                                 foreach (TypedValue tv in rb)
                                 {
                                     switch ((DxfCode)tv.TypeCode)
                                     {
                                         case DxfCode.ExtendedDataRegAppName:
                                             var a = tv.Value.ToString();
                                             ed.WriteMessage("\n APP Code :" + a);
                                             break;
                                         case DxfCode.ExtendedDataAsciiString:
                                             var b = tv.Value.ToString();
                                             if (b.IndexOf("tableType:") != -1)
                                             {
                                                 String[] cc = b.Split(':');
                                                 if (cc[1] == "processSop")
                                                 {
                                                     tableType = "processSop";
                                                     xDataDict["processSop"] = "true"; //SOP图纸表格
                                                     xDataDict["tableHandleId"] = processHandleId;
                                                 }
                                                 if (cc[1] == "processBom")
                                                 {
                                                     tableType = "processBom";
                                                     xDataDict["processBom"] = "true"; //工艺图纸表格
                                                     xDataDict["tableHandleId"] = processHandleId;
                                                 }
                                                 if (cc[1] == "productBom")
                                                 {
                                                     tableType = "productBom";
                                                     xDataDict["productBom"] = "true"; //产品图纸表格
                                                     xDataDict["tableHandleId"] = processHandleId;
                                                 }
                                             }
                                             else if (b.IndexOf("processName:") != -1)
                                             {
                                                 ed.WriteMessage("\n Process Name :" + b);
                                                 String[] cc = b.Split(':');
                                                 selectedProcessName = cc[1];
                                                 xDataDict["processName"] = cc[1];
                                                 xDataDict["tableHandleId"] = processHandleId;
                                             }
                                             else if (b.IndexOf("productCode:") != -1)
                                             {
                                                 ed.WriteMessage("\n Product Code :" + b);
                                                 String[] cc = b.Split(':');
                                                 selectedProductCode = cc[1];
                                                 xDataDict["productCode"] = cc[1];
                                                 checkProductCode = true;
                                             }
                                             else
                                             {
                                                 ed.WriteMessage("\n Product Code :" + b);
                                                 selectedProductCode = b;
                                                 checkProductCode = true;
                                                 xDataDict["productCode"] = b;
                                                 xDataDict["oldTable"] = "true";
                                                 tableType = "oldTable";
                                                 xDataDict["tableHandleId"] = processHandleId;
                                             }
                                             break;
                                         // 其他类型的DXF组码...

                                     }
                                 }
                                 tableDict[tableType] = xDataDict;
                             }
                             else
                             {
                                 ed.WriteMessage("\n实体没有扩展数据！");
                             }
                         }

                     }
                     if (!checkProductCode)
                     {
                         ed.WriteMessage("\n选择框内没有定义工艺数据！");
                         //return;
                     }
                     else
                     {
                         if (tableDict["productBom"]["productBom"] == "true" && tableDict["processBom"]["processBom"] == "false" && tableDict["processSop"]["processSop"] == "false")
                         {
                             ed.WriteMessage("\n选择框内没有定义工艺数据！");
                             //return;
                         }
                     }

                     selectedProductCode = result["图号"];

                     if (selectedProductCode == null)
                     {
                         selectedProductCode = "code";
                     }

                     //if (selectedProductCode == "")
                     //{

                     //}

                     Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                     if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                     {
                         PlotEngine pe = PlotFactory.CreatePublishEngine();
                         using (pe)
                         {
                             PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true);
                             using (ppd)
                             {
                                 int numSheet = 1;
                                 // Setting up the PlotProgress dialog
                                 ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
                                 ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                 ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                 ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                                 ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                 ppd.LowerPlotProgressRange = 0;
                                 ppd.UpperPlotProgressRange = 100;
                                 ppd.PlotProgressPos = 0;


                                 ppd.OnBeginPlot();
                                 ppd.IsVisible = true;
                                 pe.BeginPlot(ppd, null);

                                 ppd.StatusMsgString = "Plotting block 1";
                                 ppd.OnBeginSheet(); //????
                                 ppd.LowerSheetProgressRange = 0;
                                 ppd.UpperSheetProgressRange = 100;
                                 ppd.SheetProgressPos = 0;

                                 PlotInfoValidator piv = new PlotInfoValidator();
                                 piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                 PlotPageInfo ppi = new PlotPageInfo();
                                 PlotInfo pi = new PlotInfo();
                                 //BlockReference blk = gblk.BlockRef;
                                 //Layout lo = btr.LayoutObj;

                                 //// Getting coodinates of window to plot
                                 //Extents3d ext = (Extents3d)blk.Bounds;
                                 //Point3d first = ext.MaxPoint;
                                 //Point3d second = ext.MinPoint;
                                 //ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                                 //double[] firres = new double[] { 0, 0, 0 };
                                 //double[] secres = new double[] { 0, 0, 0 };
                                 //acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                                 //acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                                 //Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                                 // We need a PlotSettings object based on the layout settings which we then customize
                                 PlotSettings ps = new PlotSettings(lo.ModelType);
                                 //ps.PlotPlotStyles = true;
                                 // Specify the plot options

                                 LayoutManager.Current.CurrentLayout = lo.LayoutName;
                                 pi.Layout = lo.Id;
                                 ps.CopyFrom(lo);
                                 ps.PrintLineweights = true;
                                 ps.PlotTransparency = false;
                                 ps.PlotPlotStyles = true;
                                 ps.DrawViewportsFirst = true;
                                 ps.ShowPlotStyles = true;
                                 //PlotStyleTable = GetVauleFromArray("CtbThinnerLinesName")
                                 // The PlotSettingsValidator helps create a valid PlotSettings object
                                 PlotSettingsValidator psv = PlotSettingsValidator.Current;
                                 psv.SetPlotConfigurationName(ps, PrinterName, PaperSize);
                                 psv.RefreshLists(ps);
                                 psv.SetPlotWindowArea(ps, window);
                                 psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                 psv.SetUseStandardScale(ps, true);
                                 psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                                 psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                                 psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

                                 psv.SetPlotCentered(ps, true);

                                 pi.OverrideSettings = ps;
                                 piv.Validate(pi);
                                 if (selectedProcessName != "")
                                 {
                                     OutPath = GValues.pdfPath + "\\" + selectedProductCode + "-process-" + selectedProcessName + "-" + tableDict["processSop"]["tableHandleId"] + ".pdf";
                                 }
                                 else
                                 {
                                     OutPath = GValues.pdfPath + "\\" + selectedProductCode + ".pdf";
                                 }

                                 pe.BeginDocument(pi, doc.Name, null, 1, true, OutPath); // Create document for the first page

                                 // Plot the window
                                 pe.BeginPage(ppi, pi, true, null);
                                 pe.BeginGenerateGraphics(null);
                                 ppd.SheetProgressPos = 50;
                                 pe.EndGenerateGraphics(null);

                                 // Finish the sheet
                                 pe.EndPage(null);
                                 ppd.SheetProgressPos = 100;
                                 ppd.PlotProgressPos = 100; //+= Convert.ToInt32(100 / BlocksToPlot.Count);
                                 ppd.OnEndSheet();
                                 // Finish the document and finish the plot
                                 pe.EndDocument(null);

                                 ppd.PlotProgressPos = 100;
                                 ppd.OnEndPlot();
                                 pe.EndPlot(null);
                                 ed.WriteMessage("\nPlot completed successfully!\n\n");
                                 ps.Dispose();
                                 pe.Dispose();
                                 ppd.Dispose();
                             }
                         }
                     }
                     else
                     {
                         ed.WriteMessage("\nAnother plot is in progress.\n\n");
                     }
                     tr.Commit();
                     tr.Dispose();
                     BomForm bomForm = new BomForm();
                     bomForm.TT7SaveBomFormData(selectedProductCode, result);

                 }

             }
             catch (Autodesk.AutoCAD.Runtime.Exception e)
             {

             }
             finally
             {

             }
         }

         public void BaigeBlockToPDF(Point3d first1, Point3d second2,int type)
         {
             InitDomainConfig();
             getUserInfo();
             Dictionary<String, String> result = new Dictionary<string, string>();
             String OutPath = "";
             String processHandleId = "";
             Boolean checkProductCode = false;
             Directory.CreateDirectory(GValues.pdfPath);
             Dictionary<String, Dictionary<String, String>> tableDict = new Dictionary<string, Dictionary<string, string>>();
             SetObject setObject = new SetObject();
             setObject.initTableDictData(tableDict);
             try
             {

                 String BlockName;
                 String PrinterName = "DWG To PDF.pc3";

                 String PaperSize = "ISO_full_bleed_A4_(210.00_x_297.00_MM)";//"ISO_A4_(210.00_x_297.00_MM)";
                 Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                 Editor ed = doc.Editor;
                 Database db = doc.Database;
                 Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);

                 //PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                 //ppo.AllowNone = false;
                 //PromptPointResult ppr = ed.GetPoint(ppo);
                 //if (ppr.Status != PromptStatus.OK)
                 //    return;
                 //Point3d first1 = ppr.Value;
                 //PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", first1);
                 //ppr = ed.GetCorner(pco);
                 //if (ppr.Status != PromptStatus.OK)
                 //    return;
                 //Point3d second2 = ppr.Value;

                 //
                 // 获取当前视图方向
                 Vector3d viewDir = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;

                 // 获取当前视图位置
                 Point3d viewPos = ed.GetCurrentView().Target;

                 // 构造视图变换矩阵
                 Matrix3d viewTransform = Matrix3d.WorldToPlane(viewDir).Inverse();
                 //viewTransform = Matrix3d.Displacement(viewPos.GetAsVector()) * viewTransform;

                 //// 将WCS坐标转换为DCS坐标
                 Point3d first = first1.TransformBy(viewTransform);
                 Point3d second = second2.TransformBy(viewTransform);


                 ///====

                 // Transform from UCS to DCS
                 ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                 double[] firres = new double[] { 0, 0, 0 };
                 double[] secres = new double[] { 0, 0, 0 };
                 // Transform the first point...
                 acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                 // ... and the second
                 acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                 // We can safely drop the Z-coord at this stage
                 Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                 //Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT");
                 //Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                 Transaction tr = db.TransactionManager.StartTransaction();
                 using (tr)
                 {
                     // We'll be plotting the current layout
                     BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);

                     // 定义过滤条件，设置仅选择BlockReference

                     //SelectionFilter filter = new SelectionFilter(new TypedValue[]
                     //{
                     //    new TypedValue((int)DxfCode.Start, "TEXT") // "INSERT"代表图块引用
                     //});
                     // 使用选取窗口和过滤条件进行选择
                     PromptSelectionResult selectionResult = ed.SelectCrossingWindow(first, second);

                     // 检查选择结果
                     if (selectionResult.Status != PromptStatus.OK)
                     {
                         ed.WriteMessage("\n未选择对象或操作取消。");
                         return;
                     }
                     //Dictionary<String, String> fieldDict = new Dictionary<string, string>();
                     selectedProcessName = "";
                     SelectionSet sSet = selectionResult.Value;
                     ObjectId[] selectedIds = sSet.GetObjectIds();  // 获取选择对象的ObjectiID数组.
                     foreach (ObjectId objId in selectedIds)
                     {
                         Entity entity = tr.GetObject(objId, OpenMode.ForRead) as Entity;

                         if (entity is BlockReference)
                         {
                             BlockReference blockRef = entity as BlockReference;
                             // 获取块引用所在的图层
                             string layerName = blockRef.Layer;
                             // 获取块的名称
                             string blockName = blockRef.Name;
                             // 输出块引用的信息
                             ed.WriteMessage("\n在图层 {0} 找到块引用: {1}", layerName, blockName);

                             // 遍历块引用中的所有属性
                             foreach (ObjectId attId in blockRef.AttributeCollection)
                             {
                                 AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead);
                                 if (attRef.Tag == GValues.BlockField_SemiProductCode) // "图号"
                                 {
                                     result["图号"] = attRef.TextString;
                                 }
                                 if (attRef.Tag.IndexOf("製程") != -1)
                                 {
                                     result[attRef.Tag] = attRef.TextString;
                                 }
                                 ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                             }
                         }

                         if (entity is Table)
                         {

                             Table table = entity as Table;
                             // 你现在可以使用table对象了
                             // ...
                             processHandleId = table.Handle.Value.ToString();
                             if (table.XData != null)
                             {
                                 Dictionary<String, String> xDataDict = new Dictionary<string, string>();
                                 String tableType = "none";
                                 ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                 // 遍历ResultBuffer以查看数据
                                 foreach (TypedValue tv in rb)
                                 {
                                     switch ((DxfCode)tv.TypeCode)
                                     {
                                         case DxfCode.ExtendedDataRegAppName:
                                             var a = tv.Value.ToString();
                                             ed.WriteMessage("\n APP Code :" + a);
                                             break;
                                         case DxfCode.ExtendedDataAsciiString:
                                             var b = tv.Value.ToString();
                                             if (b.IndexOf("tableType:") != -1)
                                             {
                                                 String[] cc = b.Split(':');
                                                 if (cc[1] == "processSop")
                                                 {
                                                     tableType = "processSop";
                                                     xDataDict["processSop"] = "true"; //SOP图纸表格
                                                     xDataDict["tableHandleId"] = processHandleId;
                                                 }
                                                 if (cc[1] == "processBom")
                                                 {
                                                     tableType = "processBom";
                                                     xDataDict["processBom"] = "true"; //工艺图纸表格
                                                     xDataDict["tableHandleId"] = processHandleId;
                                                 }
                                                 if (cc[1] == "productBom")
                                                 {
                                                     tableType = "productBom";
                                                     xDataDict["productBom"] = "true"; //产品图纸表格
                                                     xDataDict["tableHandleId"] = processHandleId;
                                                 }
                                             }
                                             else if (b.IndexOf("processName:") != -1)
                                             {
                                                 ed.WriteMessage("\n Process Name :" + b);
                                                 String[] cc = b.Split(':');
                                                 selectedProcessName = cc[1];
                                                 xDataDict["processName"] = cc[1];
                                                 xDataDict["tableHandleId"] = processHandleId;
                                             }
                                             else if (b.IndexOf("productCode:") != -1)
                                             {
                                                 ed.WriteMessage("\n Product Code :" + b);
                                                 String[] cc = b.Split(':');
                                                 selectedProductCode = cc[1];
                                                 xDataDict["productCode"] = cc[1];
                                                 checkProductCode = true;
                                             }
                                             else
                                             {
                                                 ed.WriteMessage("\n Product Code :" + b);
                                                 selectedProductCode = b;
                                                 checkProductCode = true;
                                                 xDataDict["productCode"] = b;
                                                 xDataDict["oldTable"] = "true";
                                                 tableType = "oldTable";
                                                 xDataDict["tableHandleId"] = processHandleId;
                                             }
                                             break;
                                         // 其他类型的DXF组码...

                                     }
                                 }
                                 tableDict[tableType] = xDataDict;
                             }
                             else
                             {
                                 ed.WriteMessage("\n实体没有扩展数据！");
                             }
                         }

                     }
                     if (!checkProductCode)
                     {
                         ed.WriteMessage("\n选择框内没有定义工艺数据！");
                         //return;
                     }
                     else
                     {
                         if (tableDict["productBom"]["productBom"] == "true" && tableDict["processBom"]["processBom"] == "false" && tableDict["processSop"]["processSop"] == "false")
                         {
                             ed.WriteMessage("\n选择框内没有定义工艺数据！");
                             //return;
                         }
                     }

                     selectedProductCode = result["图号"];

                     if (selectedProductCode == null)
                     {
                         selectedProductCode = "code";
                     }

                     //if (selectedProductCode == "")
                     //{
                         
                     //}

                     Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                     if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                     {
                         PlotEngine pe = PlotFactory.CreatePublishEngine();
                         using (pe)
                         {
                             PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true);
                             using (ppd)
                             {
                                 int numSheet = 1;
                                 // Setting up the PlotProgress dialog
                                 ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress");
                                 ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                 ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                 ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                                 ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                 ppd.LowerPlotProgressRange = 0;
                                 ppd.UpperPlotProgressRange = 100;
                                 ppd.PlotProgressPos = 0;


                                 ppd.OnBeginPlot();
                                 ppd.IsVisible = true;
                                 pe.BeginPlot(ppd, null);

                                 ppd.StatusMsgString = "Plotting block 1";
                                 ppd.OnBeginSheet(); //????
                                 ppd.LowerSheetProgressRange = 0;
                                 ppd.UpperSheetProgressRange = 100;
                                 ppd.SheetProgressPos = 0;

                                 PlotInfoValidator piv = new PlotInfoValidator();
                                 piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                 PlotPageInfo ppi = new PlotPageInfo();
                                 PlotInfo pi = new PlotInfo();
                                 //BlockReference blk = gblk.BlockRef;
                                 //Layout lo = btr.LayoutObj;

                                 //// Getting coodinates of window to plot
                                 //Extents3d ext = (Extents3d)blk.Bounds;
                                 //Point3d first = ext.MaxPoint;
                                 //Point3d second = ext.MinPoint;
                                 //ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2));
                                 //double[] firres = new double[] { 0, 0, 0 };
                                 //double[] secres = new double[] { 0, 0, 0 };
                                 //acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                                 //acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                                 //Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                                 // We need a PlotSettings object based on the layout settings which we then customize
                                 PlotSettings ps = new PlotSettings(lo.ModelType);
                                 //ps.PlotPlotStyles = true;
                                 // Specify the plot options

                                 LayoutManager.Current.CurrentLayout = lo.LayoutName;
                                 pi.Layout = lo.Id;
                                 ps.CopyFrom(lo);
                                 ps.PrintLineweights = true;
                                 ps.PlotTransparency = false;
                                 ps.PlotPlotStyles = true;
                                 ps.DrawViewportsFirst = true;
                                 ps.ShowPlotStyles = true;
                                 //PlotStyleTable = GetVauleFromArray("CtbThinnerLinesName")
                                 // The PlotSettingsValidator helps create a valid PlotSettings object
                                 PlotSettingsValidator psv = PlotSettingsValidator.Current;
                                 psv.SetPlotConfigurationName(ps, PrinterName, PaperSize);
                                 psv.RefreshLists(ps);
                                 psv.SetPlotWindowArea(ps, window);
                                 psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                 psv.SetUseStandardScale(ps, true);
                                 psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                                 psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                                 psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

                                 psv.SetPlotCentered(ps, true);

                                 pi.OverrideSettings = ps;
                                 piv.Validate(pi);
                                 if (selectedProcessName != "")
                                 {
                                     OutPath = GValues.pdfPath + "\\" + selectedProductCode + "-process-" + selectedProcessName + "-" + tableDict["processSop"]["tableHandleId"] + ".pdf";
                                 }
                                 else
                                 {
                                     if (type == 1)
                                     {
                                         OutPath = GValues.pdfPath + "\\" + selectedProductCode + ".pdf";
                                     }
                                     else if (type == 2)
                                     {
                                         OutPath = GValues.pdfPath + "\\" + selectedProductCode + "-material.pdf";
                                     }
                                     else
                                     {
                                         OutPath = GValues.pdfPath + "\\" + selectedProductCode + "-other.pdf";
                                     }
                                    
                                 }

                                 pe.BeginDocument(pi, doc.Name, null, 1, true, OutPath); // Create document for the first page

                                 // Plot the window
                                 pe.BeginPage(ppi, pi, true, null);
                                 pe.BeginGenerateGraphics(null);
                                 ppd.SheetProgressPos = 50;
                                 pe.EndGenerateGraphics(null);

                                 // Finish the sheet
                                 pe.EndPage(null);
                                 ppd.SheetProgressPos = 100;
                                 ppd.PlotProgressPos = 100; //+= Convert.ToInt32(100 / BlocksToPlot.Count);
                                 ppd.OnEndSheet();
                                 // Finish the document and finish the plot
                                 pe.EndDocument(null);

                                 ppd.PlotProgressPos = 100;
                                 ppd.OnEndPlot();
                                 pe.EndPlot(null);
                                 ed.WriteMessage("\nPlot completed successfully!\n\n");
                                 ps.Dispose();
                                 pe.Dispose();
                                 ppd.Dispose();
                             }
                         }
                     }
                     else
                     {
                         ed.WriteMessage("\nAnother plot is in progress.\n\n");
                     }
                     tr.Commit();
                     tr.Dispose();
                     BomForm bomForm = new BomForm();
                     bomForm.TT7SaveBomFormData(selectedProductCode, result);

                 }

             }
             catch (Autodesk.AutoCAD.Runtime.Exception e)
             {

             }
             finally
             {

             }
         }

         [CommandMethod("SetLayer0XData")]
         public static void SetLayer0XData()
         {
             Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
             Database db = doc.Database;

             using (Transaction tr = db.TransactionManager.StartTransaction())
             {
                 // 获取图层表
                 LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                 // 确保0图层存在
                 if (!lt.Has("0"))
                 {
                     lt.UpgradeOpen();
                     LayerTableRecord ltr = new LayerTableRecord();
                     ltr.Name = "0";
                     lt.Add(ltr);
                     tr.AddNewlyCreatedDBObject(ltr, true);
                 }

                 // 打开0图层记录
                 LayerTableRecord layer0 = tr.GetObject(lt["0"], OpenMode.ForWrite) as LayerTableRecord;

                 // 注册应用程序名（必须先在数据库中注册）
                 //RegAppTable rat = tr.GetObject(db.RegAppTableId, OpenMode.ForRead) as RegAppTable;
                 //if (!rat.Has("ACAD"))
                 //{
                 //    rat.UpgradeOpen();
                 //    RegAppTableRecord ratr = new RegAppTableRecord();
                 //    ratr.Name = "ACAD";
                 //    rat.Add(ratr);
                 //    tr.AddNewlyCreatedDBObject(ratr, true);
                 //}

                 // 创建扩展数据
                 ResultBuffer rb = new ResultBuffer(
                     new TypedValue(1001, "ACAD"),         // 应用程序名
                     new TypedValue(1000, "数据标识"),       // 字符串类型
                     new TypedValue(1070, 2024),            // 整型数据
                     new TypedValue(1040, 3.1415)           // 浮点型数据
                 );

                 // 附加扩展数据到图层
                 layer0.XData = rb;
                 rb.Dispose();

                 tr.Commit();
             }
         }

        [CommandMethod("ReadLayer0XData")]
    public static void ReadLayer0XData()
    {
        Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        Database db = doc.Database;
        
        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            // 获取0图层记录
            LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
            LayerTableRecord layer0 = tr.GetObject(lt["0"], OpenMode.ForRead) as LayerTableRecord;
            
            // 获取指定应用的扩展数据
            ResultBuffer rb = layer0.GetXDataForApplication("ACAD");
            
            if (rb == null)
            {
                doc.Editor.WriteMessage("\n未找到ACAD的扩展数据");
                return;
            }

            // 解析扩展数据
            doc.Editor.WriteMessage("\n扩展数据内容：");
            foreach (TypedValue tv in rb)
            {
                doc.Editor.WriteMessage("\n类型码:" + tv.TypeCode + " 值:" +tv.Value);
            }
            
            rb.Dispose();
            tr.Commit();
        }
    }
         [CommandMethod("UnlockAllLayer")]
         public void UnlockAllLayer()
         {
             // 获取当前文档和数据库
             Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
             Database db = doc.Database;
             Editor ed = doc.Editor;
             DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
             // 启动事务
             using (Transaction tr = db.TransactionManager.StartTransaction())
             {
                 // 打开图层表
                 LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                 // 遍历所有图层
                 foreach (ObjectId layerId in lt)
                 {
                     // 打开图层表记录
                     LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForRead);

                     // 检查图层是否锁定
                     if (ltr.IsLocked)
                     {
                         // 解锁图层
                         ltr.UpgradeOpen();
                         ltr.IsLocked = false;
                         ltr.DowngradeOpen();
                     }
                 }

                 // 打开块表
                 BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                 // 遍历模型空间、图纸空间等所有块表记录
                 foreach (ObjectId btrId in bt)
                 {
                     BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead);
                     int count = 0;

                 }
                 //SelectBlock2Pdf block2Pdf = new SelectBlock2Pdf();
                 //Point3d first = new Point3d(-119672.61, -34907.53, 0);
                 //Point3d secord = new Point3d(-116898.3, -32974.14, 0);
                 //block2Pdf.PlotBlockColToPDF(first, secord, "test");
                 docLock.Dispose();
                 // 提交事务
                 tr.Commit();
             }
         }
        [CommandMethod("HONGSHENGFEI")]
         public void HongShengFei()
         {
             if (hongShengFeiForm == null || hongShengFeiForm.IsDisposed)
             {
                 hongShengFeiForm = new HongShengFeiForm();
             }
             Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, hongShengFeiForm);
         }

        [CommandMethod("FUYUAN")]
        public void Fuyuan()
        {
            if (fuYuanForm == null || fuYuanForm.IsDisposed)
            {
                fuYuanForm = new FuYuanForm();
            }
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, fuYuanForm);
        }

        [CommandMethod("BAIGE")]
        public void Baige()
        {
            if (baigeForm == null || baigeForm.IsDisposed)
            {
                baigeForm = new BaiGeForm();
            }
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, baigeForm);
        }

        [CommandMethod("UnlockAllLayersAndReadObject")]
        public void UnlockAllLayersAndReadObject()
        {
            // 获取当前文档和数据库
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            // 启动事务
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 打开图层表
                LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                // 遍历所有图层
                foreach (ObjectId layerId in lt)
                {
                    // 打开图层表记录
                    LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForRead);

                    // 检查图层是否锁定
                    if (ltr.IsLocked)
                    {
                        // 解锁图层
                        ltr.UpgradeOpen();
                        ltr.IsLocked = false;
                        ltr.DowngradeOpen();
                    }
                }

                // 打开块表
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                // 遍历模型空间、图纸空间等所有块表记录
                foreach (ObjectId btrId in bt)
                {
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead);
                    int count = 0;
                    foreach (ObjectId objId in btr)
                    {
                        Entity ent = (Entity)tr.GetObject(objId, OpenMode.ForRead);

                        if (ent is BlockReference )
                        {
                            count++;
                            BlockReference blockRef = ent as BlockReference;
                            MessageBox.Show(blockRef.ScaleFactors.X.ToString());
                            MessageBox.Show(blockRef.Name);
                            Point3d position = blockRef.Position;
                            MessageBox.Show(position.X.ToString() + "   " + position.Y.ToString());
                             // 获取块定义的基点
                             btr = tr.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;

                            Point3d basePoint = btr.Origin;

                            // 获取包围盒范围
                            Extents3d extents = new Extents3d();
                            try
                            {
                                extents = blockRef.Bounds.Value;
                            }
                            catch
                            {
                                extents = new Extents3d(position, position); // 处理空包围盒
                            }
                            string code = "";

                            // 遍历块引用中的所有属性
                            foreach (ObjectId attId in blockRef.AttributeCollection)
                            {
                                AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead);
                                if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                                {
                                    code = attRef.TextString;
                                    //result["图号"] = attRef.TextString;
                                }
                                if (attRef.Tag.IndexOf("製程") != -1)
                                {
                                    //result[attRef.Tag] = attRef.TextString;
                                }
                                ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                            }

                             // 写入信息
                             ed.WriteMessage("实例 {0}:",count);
                             ed.WriteMessage("插入点位置: X={0}, Y={1}, Z={2}", position.X, position.Y, position.Z);
                             ed.WriteMessage("块定义基点: X={0}, Y={1}, Z={2}", basePoint.X, basePoint.Y, basePoint.Z);
                             ed.WriteMessage("包围盒范围:");
                             ed.WriteMessage(" 最小点: X={0}, Y={1}, Z={2}", blockRef.DynamicBlockTableRecord.Database.Extmin.X, blockRef.DynamicBlockTableRecord.Database.Extmin.Y, blockRef.DynamicBlockTableRecord.Database.Extmin.Z);
                             ed.WriteMessage(" 最大点: X={0}, Y={1}, Z={2}", blockRef.DynamicBlockTableRecord.Database.Extmax.X, blockRef.DynamicBlockTableRecord.Database.Extmax.Y, blockRef.DynamicBlockTableRecord.Database.Extmax.Z);

                            // 获取块引用所在的图层
                            string layerName = blockRef.Layer;
                            // 获取块的名称
                            string blockName = blockRef.Name;
                            // 输出块引用的信息
                            ed.WriteMessage("\n在图层 {0} 找到块引用: {1}", layerName, blockName);
                            SelectBlock2Pdf block2Pdf = new SelectBlock2Pdf();
                            //Point3d first = new Point3d(-114496.11, 15650.83, 0);
                            //Point3d secord = new Point3d(-107951.96, 20211.37, 0);
                            Point3d first = new Point3d(44582.01, 14753.37, 0);
                            Point3d secord = new Point3d(45495.94, 15390.28, 0);
                            block2Pdf.PlotBlockColToPDF(first,secord, code);
                        }
                    }
                }
                docLock.Dispose();
                // 提交事务
                tr.Commit();
            }
        }



        [CommandMethod("GetBlockExtents")]
    public void GetBlockExtents()
    {
        // 获取当前文档和编辑器
        Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        Editor acEd = acDoc.Editor;
 
        // 提示用户选择一个或多个块
        PromptSelectionResult selRes = acEd.SelectImplied();
        if (selRes.Status != PromptStatus.OK) return;
        SelectionSet selSet = selRes.Value;
 
        // 遍历所有选中的对象
        foreach (SelectedObject selObj in selSet)
        {
            // 检查对象类型是否为块引用
            if (selObj.ObjectId.ObjectClass.Name == "AcDbBlockReference")
            {
                using (Transaction tr = acDoc.TransactionManager.StartTransaction())
                {
                    try
                    {
                        // 打开对象以读取其属性
                        BlockReference blockRef = tr.GetObject(selObj.ObjectId, OpenMode.ForRead) as BlockReference;
                        if (blockRef != null)
                        {
                            // 获取块的边界框（对角坐标）
                            Extents3d extents = (Extents3d) blockRef.Bounds;
                            Point3d minPoint = extents.MinPoint; // 最小点坐标
                            Point3d maxPoint = extents.MaxPoint; // 最大点坐标
 
                            // 输出或处理坐标信息
                            acEd.WriteMessage("Block Name: {blockRef.Name}" + blockRef.Name);
                            acEd.WriteMessage("Min Point: {minPoint}" + minPoint);
                            acEd.WriteMessage("Max Point: {maxPoint}" + maxPoint);
                        }
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception ex)
                    {
                        acEd.WriteMessage("Error: {ex.Message}" + ex.Message);
                    }
                    finally
                    {
                        tr.Commit(); // 提交事务
                    }
                }
            }
        }
    }


        [CommandMethod("BlockToNewDwg")]
        public void BlockToNewDwg()
        {
            SelectBlock2Pdf block2Pdf = new SelectBlock2Pdf();
            block2Pdf.BlockToNewDwg();


        }

        [CommandMethod("ReadDwgFile")]
        public void readDwgFile()
        {
            SelectBlock2Pdf block2Pdf = new SelectBlock2Pdf();
            block2Pdf.ConvertDwgToPdf();


        }
        [CommandMethod("SelectBlock2PDF")]
         public void SelectBlock2PDF()
         {
            SelectBlock2Pdf select2pdf = new SelectBlock2Pdf();
            //select2pdf.PlotBlockColToPDF();
         }

        [CommandMethod("ExportBlockToPdf")]
        public void ExportBlockToPdf()
        {
            // 指定 DWG 文件的路径
            string dwgFilePath = @"D:\工程图\11HZXC304-1.dwg";
            // 指定输出 PDF 文件的路径
            string pdfFilePath = @"C:\path\to\output\file.pdf";

            try
            {
                // 创建一个新的 Database 对象
                using (Database db = new Database(false, true))
                {
                    // 打开 DWG 文件
                    db.ReadDwgFile(dwgFilePath, FileOpenMode.OpenForReadAndReadShare, false, null);

                    // 启动事务
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        // 打开块表
                        BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                        // 打开模型空间块表记录
                        BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                        // 打开对象以读取其属性
                        // 遍历模型空间中的所有对象，选择所有块参照
                        foreach (ObjectId objId in btr)
                        {
                            Entity ent = (Entity)tr.GetObject(objId, OpenMode.ForRead);
                            if (ent is BlockReference)
                            {
                                BlockReference blockRef = (BlockReference)ent;
                                if (blockRef != null)
                                {
                                    SelectBlock2Pdf block2Pdf = new SelectBlock2Pdf();
                                    block2Pdf.PlotBlockColToPDF(blockRef.DynamicBlockTableRecord.Database.Extmin, blockRef.DynamicBlockTableRecord.Database.Extmax, "1234");
                                }
                            }
                        }


                    }
                }

                Console.WriteLine("块已成功输出到 PDF 文件。");
            }
            catch (System.Exception ex)
            {

            }
        }

         [CommandMethod("CheckObjectXdata")]
         public void CheckObjectXdata()
         {
             Dictionary<String, String> result = new Dictionary<string, string>();

             int count = 0;

             Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
             Database db = doc.Database;
             Editor ed = doc.Editor;
             List<String> handleIds = new List<string>();
             DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
             PromptSelectionOptions pso = new PromptSelectionOptions();
             pso.MessageForAdding = "\n请选择图形";
             pso.MessageForRemoval = "\n请移除图形";
             PromptSelectionResult psr = ed.GetSelection(pso);
             List<String> pointCenters = new List<string>();
             if (psr.Status != PromptStatus.OK)
             {
                 ed.WriteMessage("\n未选择任何对象。");
                 return;
             }
             SelectionSet ss = psr.Value;
             ObjectId[] selectedIds = ss.GetObjectIds();

             using (Transaction tr = doc.TransactionManager.StartTransaction())
             {
                 // 打开图层表
                 LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                 // 遍历所有图层
                 foreach (ObjectId layerId in lt)
                 {
                     // 打开图层表记录
                     LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForRead);

                     // 检查图层是否锁定
                     if (ltr.IsLocked)
                     {
                         // 解锁图层
                         ltr.UpgradeOpen();
                         ltr.IsLocked = false;
                         ltr.DowngradeOpen();
                     }
                 }

                 
                // 打开块表
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                // 遍历模型空间、图纸空间等所有块表记录
                foreach (ObjectId btrId in bt)
                {
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead);
                    foreach (ObjectId objId in btr)
                    {
                        Entity ent = (Entity)tr.GetObject(objId, OpenMode.ForRead);
                        if (ent is BlockReference)
                        {
                            BlockReference blockRef = ent as BlockReference;
                            
                            // 获取块的边界框
                            //Extents3d extents = (Extents3d)blockRef.Bounds;
 
                            //// 最小点（左下角）
                            //Point3d minPoint = extents.MinPoint;
 
                            //// 最大点（右上角）
                            //Point3d maxPoint = extents.MaxPoint;
 
                            //// 输出对角坐标
                            // ed.WriteMessage("\n  最小坐标: {0}, 最大坐标: {1}", minPoint, maxPoint);


                            // 获取块引用所在的图层
                            string layerName = blockRef.Layer;
                            // 获取块的名称
                            string blockName = blockRef.Name;
                            // 输出块引用的信息
                            ed.WriteMessage("\n在图层 {0} 找到块引用: {1}", layerName, blockName);

                            // 遍历块引用中的所有属性
                            foreach (ObjectId attId in blockRef.AttributeCollection)
                            {
                                AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead);
                                if (attRef.Tag == GValues.BlockField_SemiProductCode ) //"图号"
                                {
                                    result["图号"] = attRef.TextString;
                                }
                                if (attRef.Tag.IndexOf("製程") != -1)
                                {
                                    result[attRef.Tag] = attRef.TextString;
                                }
                                ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                            }
                        }
                    }
                }


                 foreach (ObjectId id in selectedIds)
                 {
                     Entity entity = tr.GetObject(id, OpenMode.ForWrite) as Entity;

                     if (entity.XData != null)
                     {
                         ResultBuffer rb = entity.XData; // 获取实体的扩展数据

                         // 遍历ResultBuffer以查看数据
                         foreach (TypedValue tv in rb)
                         {
                             switch ((DxfCode)tv.TypeCode)
                             {
                                 case DxfCode.ExtendedDataRegAppName:
                                     String regAppName = tv.ToString();
                                     ed.WriteMessage("\n找到的app字符串： " + regAppName);
                                     break;
                                 case DxfCode.ExtendedDataAsciiString:
                                     String asciiData = tv.ToString();
                                     ed.WriteMessage("\n找到的ASCII字符串： " + asciiData);
                                     break;
                                 //case DxfCode.ExtendedDataLayerName:
                                 //    controlData = tv.ToString();
                                 //    break;
                                 // 其他类型的DXF组码...
                             }
                         }
                     }
                     //if (entity != null)
                     //{
                     //    if (entity is Circle)
                     //    {
                     //        Circle c = entity as Circle;
                     //        pointCenters.Add(c.Center.X.ToString() + "-" + c.Center.Y.ToString());
                     //        entity.Erase();
                     //    }
                     //    if (entity is Arc)
                     //    {
                     //        entity.Erase();
                     //    }
                     //}
                 }
                 //pointCenters = pointCenters.Distinct().ToList();
                 //count = pointCenters.Count;
                 foreach (String centerPoint in pointCenters)
                 {
                     //Point3d point3d = new Point3d(double.Parse(centerPoint.Split('-')[0]), double.Parse(centerPoint.Split('-')[1]), 0);
                     //DBText text = new DBText
                     //{
                     //    //TextString = propertys[0].label,
                     //    //Position = new Point3d(point3d.X + 10, point3d.Y + 10, point3d.Z),
                     //    //Height = 10, //设置文本高度
                     //    //ColorIndex = getColorIndex(propertys[0].color.ToString())
                     //};

                     //BlockTableRecord btr = tr.GetObject(doc.Database.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                     //btr.AppendEntity(text);
                     //tr.AddNewlyCreatedDBObject(text, true);
                     //handleIds.Add(text.Handle.Value.ToString());
                     //foreach (MrpProductBomMaterialProperty property in propertys)
                     //{
                     //    Circle circle = new Circle();
                     //    circle = new Circle(point3d, Vector3d.ZAxis, double.Parse(property.redius));
                     //    //circle.Color = Color.FromRgb(255, 0,0);
                     //    circle.ColorIndex = getColorIndex(property.color);

                     //    btr.AppendEntity(circle);
                     //    tr.AddNewlyCreatedDBObject(circle, true);
                     //    handleIds.Add(circle.Handle.Value.ToString());
                     //}
                 }

                 //// 将圆添加到数据库中
                 //acCurDbase.Add(circle);

                 //// 刷新视图以显示新创建的圆
                 //acEd.Regen(Regapp.kRedraw);
                 tr.Commit();
                 docLock.Dispose();
                 doc.Editor.UpdateScreen();
                 doc.Editor.Regen();
             }
         }


         #endregion 
         private void LoginForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 当窗口关闭时，将 loginForm 设置为 null
            loginForm = null;
            sqlLite = null;
        }
        private void BomForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 当窗口关闭时，将Form 设置为 null
            bomForm.Dispose();            
            bomForm = null;
            sqlLite = null;
        }
        private void setProcessNameForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            setProcessNameForm = null;
        }
        private void InitTableEvent()
        {

        }
        #region 操作函数代码块
        public void InitDomainConfig()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor editor = doc.Editor;
            // 指定配置文件的路径
            string configFilePath = GValues.configPath; //"E:\\Program Files\\Autodesk\\AutoCAD 2014\\erptestdll\\config.txt";
            try
            {
                // 读取文本文件的所有行
                string[] lines = File.ReadAllLines(configFilePath);

                // 遍历每一行并处理配置信息
                foreach (string line in lines)
                {
                    // 假设配置文件的每一行都是以"键=值"的格式存储
                    string[] keyValue = line.Split('=');
                    if (keyValue.Length == 2)
                    {
                        string key = keyValue[0].Trim();
                        string value = keyValue[1].Trim();
                        // 在这里处理配置信息，例如存储到字典或使用
                        if (key == "domain")
                        {
                            domain = value;
                        }
                        try
                        {
                            if (key == "domainLink")
                            {
                                GValues.domainLink = value;
                            }
                            if (key == "CADCreateProductCode")
                            {
                                GValues.CADCreateProductCode = Convert.ToBoolean( value);
                            }
                            if (key == "CADCreateProductDwgFile")
                            {
                                GValues.CADCreateProductDwgFile = Convert.ToBoolean(value);
                            }
                            if (key == "CadBlockTableProcess")
                            {
                                GValues.CadBlockTableProcess = Convert.ToBoolean(value);
                            }
                            if (key == " BlockField_ProductName")
                            {
                                GValues.BlockField_ProductName = value;
                            }
                            if (key == "BlockField_TuHao")
                            {
                                GValues.BlockField_TuHao = value;
                            }
                            if (key == "BlockField_CaiLiao")
                            {
                                GValues.BlockField_CaiLiao = value;
                            }
                            if (key == "BlockField_CaiHou")
                            {
                                GValues.BlockField_CaiHou = value;
                            }
                            if (key == "BlockField_HouDu")
                            {
                                GValues.BlockField_HouDu = value;
                            }
                            if (key == "BlockField_SurfaceChuli")
                            {
                                GValues.BlockField_SurfaceChuli = value;
                            }
                            if (key == "BlockField_SemiProductName")
                            {
                                GValues.BlockField_SemiProductName = value;
                            }
                            if (key == "BlockField_ProductVer")
                            {
                                GValues.BlockField_ProductVer = value;
                            }
                            if (key == "BlockField_CustCode")
                            {
                                GValues.BlockField_CustCode = value;
                            }
                            if (key == "BlockField_CustName")
                            {
                                GValues.BlockField_CustName = value;
                            }
                            if (key == "BlockField_BomQty")
                            {
                                GValues.BlockField_BomQty = value;
                            }
                            if (key == "BlockField_Engineers")
                            {
                                GValues.BlockField_Engineers = value;
                            }
                            if (key == "BlockField_Project")
                            {
                                GValues.BlockField_Project = value;
                            }
                            if (key == "BlockField_SizeLength")
                            {
                                GValues.BlockField_SizeLength = value;
                            }
                            if (key == "BlockField_SizeWidth")
                            {
                                GValues.BlockField_SizeWidth = value;
                            }
                            if (key == "BlockField_MainProductCode")
                            {
                                GValues.BlockField_MainProductCode = value;
                            }
                            if (key == "BlockField_CustomerCode")
                            {
                                GValues.BlockField_CustomerCode = value;
                            }
                            if (key == "BlockField_CustomerShortName")
                            {
                                GValues.BlockField_CustomerShortName = value;
                            }
                            //if (key == "BlockField_SemiProductName")
                            //{
                            //    GValues.BlockField_SemiProductName = value;
                            //}
                            if (key == "BlockField_SemiProductCode")
                            {
                                GValues.BlockField_SizeWidth = value;
                            }
                            if (key == "BlockField_SemiProductCustCode")
                            {
                                GValues.BlockField_SemiProductCustCode = value;
                            }
                            if (key == "BlockField_SemiProductDrawingNo")
                            {
                                GValues.BlockField_SemiProductDrawingNo = value;
                            }
                            if (key == "BlockField_SemiProductModel")
                            {
                                GValues.BlockField_SemiProductModel = value;
                            }
                            if (key == "BlockField_SemiProductVer")
                            {
                                GValues.BlockField_SemiProductVer = value;
                            }
                            if (key == "BlockField_SemiProductDescription")
                            {
                                GValues.BlockField_SemiProductDescription = value;
                            }
                            if (key == "BlockField_SemiProductCaiLiao")
                            {
                                GValues.BlockField_SemiProductCaiLiao = value;
                            }
                            if (key == "BlockField_SemiProductCaiHou")
                            {
                                GValues.BlockField_SemiProductCaiHou = value;
                            }
                            if (key == "BlockField_SemiProductSizeLength")
                            {
                                GValues.BlockField_SemiProductSizeLength = value;
                            }
                            if (key == "BlockField_SemiProductSizeWidth")
                            {
                                GValues.BlockField_SemiProductSizeWidth = value;
                            }
                            if (key == "BlockField_SemiProductWeight")
                            {
                                GValues.BlockField_SemiProductWeight = value;
                            }
                            if (key == "BlockField_SemiProductBomQty ")
                            {
                                GValues.BlockField_SemiProductBomQty = value;
                            }
                            if (key == "BlockField_SemiProductSurfaceChuli")
                            {
                                GValues.BlockField_SemiProductSurfaceChuli = value;
                            }
                            if (key == "AutoCreateSemiProductCode")
                            {
                                GValues.AutoCreateSemiProductCode = Convert.ToBoolean(value);
                            }
                            if (key == "BlockField_LossRate")
                            {
                                GValues.BlockField_LossRate = Convert.ToDouble(value);
                            }                                                        
                            if (key == "BlockField_FenmoLossRate")
                            {
                                GValues.BlockField_FenmoLossRate = Convert.ToDouble(value);
                            }
                            if (key == "CADCreateMaterialCode")
                            {
                                GValues.CADCreateMaterialCode = Convert.ToBoolean(value);
                            }
                        }
                        catch (System.Exception e)
                        {
                            editor.WriteMessage(e.ToString());
                        }
                    }
                }
            }
            catch (IOException e)
            {
                editor.WriteMessage("读取配置文件时发生错误: " + e.Message);
            }

        }


         [CommandMethod("ExportBlockToDwg")]

            public void ExportBlockToDwg()
    {
        Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        Editor ed = doc.Editor;

        // 选择块
        PromptEntityOptions blockOptions = new PromptEntityOptions("\n请选择一个块: ");
        blockOptions.SetRejectMessage("\n选择的对象不是块。");
        blockOptions.AddAllowedClass(typeof(BlockReference), true);

        PromptEntityResult blockResult = ed.GetEntity(blockOptions);
        if (blockResult.Status != PromptStatus.OK)
            return;

        ObjectId blockId = blockResult.ObjectId;

        // 获取块的定义
        using (Transaction trans = doc.TransactionManager.StartTransaction())
        {
            BlockReference blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead);
            BlockTableRecord blockTableRecord = (BlockTableRecord)trans.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead);

            // 创建新的 DWG 文件
            string newDwgPath = "C:\\plot2pdf\\ExportedBlockContents.dwg"; // 替换为你的目标路径
            Database newDb = new Database(true, true);
            newDb.SaveAs(newDwgPath, DwgVersion.Current);

            // 将块内容复制到新的 DWG 文件
            using (Transaction newTrans = newDb.TransactionManager.StartTransaction())
            {
                BlockTableRecord newBlockTableRecord = (BlockTableRecord)newTrans.GetObject(newDb.CurrentSpaceId, OpenMode.ForWrite);

                // 复制块内部的对象
                foreach (ObjectId objId in blockTableRecord)
                {
                    DBObject dbObject = trans.GetObject(objId, OpenMode.ForRead);
                    if (dbObject is Entity )
                    {
                        Entity entity = dbObject as Entity;
                        Entity newEntity = (Entity)entity.Clone();
                        newBlockTableRecord.AppendEntity(newEntity);
                        newTrans.AddNewlyCreatedDBObject(newEntity, true);
                    }
                }

                newTrans.Commit();
            }

            trans.Commit();
        }

        ed.WriteMessage("\n块内容已导出到 {newDwgPath}");
    }


    //public void ExportBlockToDwg()
    //{
    //    Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
    //    Editor ed = doc.Editor;
    //    string newDwgPath = "";
    //    // 选择块
    //    PromptEntityOptions blockOptions = new PromptEntityOptions("\n请选择一个块: ");
    //    blockOptions.SetRejectMessage("\n选择的对象不是块。");
    //    blockOptions.AddAllowedClass(typeof(BlockReference), true);

    //    PromptEntityResult blockResult = ed.GetEntity(blockOptions);
    //    if (blockResult.Status != PromptStatus.OK)
    //        return;

    //    ObjectId blockId = blockResult.ObjectId;

    //    // 获取块的定义
    //    BlockReference blockRef;
    //    using (Transaction trans = doc.TransactionManager.StartTransaction())
    //    {
    //        blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead);
    //        BlockTableRecord blockTableRecord = (BlockTableRecord)trans.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead);

    //        // 创建新的 DWG 文件
    //        newDwgPath = "C:\\plot2pdf\\ExportedBlockContents.dwg"; // 替换为你的目标路径
    //        Database newDb = new Database(true, true);
    //        newDb.SaveAs(newDwgPath, DwgVersion.Current);

    //        // 将块内容复制到新的 DWG 文件
    //        using (Transaction newTrans = newDb.TransactionManager.StartTransaction())
    //        {
    //            BlockTableRecord newBlockTableRecord = (BlockTableRecord)newTrans.GetObject(newDb.CurrentSpaceId, OpenMode.ForWrite);

    //            // 复制块内部的对象
    //            foreach (ObjectId objId in blockTableRecord)
    //            {
    //                Entity entity = (Entity)trans.GetObject(objId, OpenMode.ForRead);
    //                Entity newEntity = (Entity)entity.Clone();
    //                newBlockTableRecord.AppendEntity(newEntity);
    //                newTrans.AddNewlyCreatedDBObject(newEntity, true);
    //            }

    //            newTrans.Commit();
    //        }

    //        trans.Commit();
    //    }

    //    ed.WriteMessage("\n块内容已导出到 {newDwgPath}" + newDwgPath);
    //}


        [CommandMethod("CadArea")]
        public void CadAreaCommand()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            // 提示用户选择图形
            PromptSelectionResult psr = ed.GetSelection();
            if (psr.Status != PromptStatus.OK)
                return;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                SelectionSet sset = psr.Value;
                ObjectId[] ids = sset.GetObjectIds();
                foreach (ObjectId id in ids)
                {
                    Entity entity = tr.GetObject(id, OpenMode.ForRead) as Entity;
                    if (entity is Autodesk.AutoCAD.DatabaseServices.Region)
                    {
                        //Polyline pl = entity as Polyline;
                        Autodesk.AutoCAD.DatabaseServices.Region pl = entity as Autodesk.AutoCAD.DatabaseServices.Region;
                        double area = pl.Area;
                        ed.WriteMessage("\n选择图形的面积是: " + area);
                    }
                    else
                    {
                        ed.WriteMessage("\n选择的图形不是多边形");
                    }
                }
                tr.Commit();
            }
        }
        [CommandMethod("CalculateArea")]
        public void CalculateArea()
        {
            Document doc =  Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            PromptEntityOptions peo = new PromptEntityOptions("\n选择图形对象以计算其面积:");
            peo.SetRejectMessage("\n只能接受几何图形对象。");
            peo.AddAllowedClass(typeof(Polyline), false);

            PromptEntityResult per = ed.GetEntity(peo);
            if (per.Status != PromptStatus.OK)
                return;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Entity entity = tr.GetObject(per.ObjectId, OpenMode.ForRead) as Entity;
                if (entity is Polyline)
                {
                    Polyline pline = entity as Polyline;
                    double area = pline.Area;
                    ed.WriteMessage("\n选择的多边形面积是: " + area);
                }
                else
                {
                    ed.WriteMessage("\n对不起，所选对象不是多边形。");
                }
                tr.Commit();
            }
        }


        private void getUserInfo(){
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor editor = doc.Editor;
            try
            {
                sqlLite = new SqlLiteUtils();
                //sqlLite.createDb();
                //String password = StringSecurity.DESEncrypt("123456");
                //sqlLite.insertData("admin", password);
                //String encode = StringSecurity.DESDecrypt(password);
                string sql = "select account,password,domainid,token from user";
                SQLiteDBHelper db = new SQLiteDBHelper(GValues.dbpath);
                using (SQLiteDataReader reader = db.ExecuteReader(sql, null))
                {
                    while (reader.Read())
                    {
                        //editor.WriteMessage(reader.GetString(0) + " " + reader.GetString(1) + "\n");
                        //Console.WriteLine("account:{0},password{1}", reader.GetString(0), reader.GetString(1));
                        GValues.account = reader.GetString(0);
                        GValues.password = StringSecurity.DESDecrypt(reader.GetString(1));
                        GValues.tenant = reader.GetString(2);
                        GValues.token = reader.GetString(3);
                    }
                }
            }
            catch (System.Exception e)
            {
                editor.WriteMessage(e.ToString());
            }
        }
        private void GetDomainTenant()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor editor = doc.Editor;
            Http.CreateHttpClient().GetAsync(GValues.domainLink + "saas/data/get?domain=" + domain, new Action<Http.HttpResp>((r) =>
            {
                var responCode = Convert.ToInt32(r.Code);
                if (responCode == 200) //访问成功
                {
                    GValues.tenant = r.AckStr();
                    loginForm.domainid = r.AckStr().ToString();
                    loginForm.enablelogin = true;
                    //editor.WriteMessage("Domain: " + r.AckStr().ToString());
                }
                else
                {
                    editor.WriteMessage(r.Code + " " + " " + responCode + " " + r.Error);
                }
            }));
        }
        #endregion
        #region bom设定对象属性及特定值
        [CommandMethod("SelectObjectSetProperty")]
        public void selectObjectSetProperty()
        {
            SetObject setObject = new SetObject();
            setObject.SetInsertTable();
        }

        [CommandMethod("AddTextNearShape")]
        public void AddTextNearShape()
        {
            SetObject setObject = new SetObject();
            setObject.AddTextNearShape();
        }
        [CommandMethod("SelectAndLabel")]
        public void SelectAndLabel()
        {
            //SetObject setObject = new SetObject();
            //setObject.SelectAndLabel(null);
        }
        [CommandMethod("OpenWindow")]
        public void openWindow()
        {
            SetObjectForm form = new SetObjectForm();
            form.Show();
            
        }
        [CommandMethod("GetTableCellHeight")]
        public void GetTableCellHeight()
        {
            SetObject setObject = new SetObject();
            setObject.GetTableTextHeight();
        }
        [CommandMethod("TTE1")]
        public void initBomMaterialQty()
        {
            try
            {
                InitDomainConfig();
                getUserInfo();
                if (setBomMaterialForm == null || setBomMaterialForm.IsDisposed)
                {
                    setBomMaterialForm = new SetBomMaterialForm();
                }
                //MessageBox.Show("ok 1");
                //NetApi netApi = new NetApi();
                //netApi.getSystemParamater(new Action<ResponResultA<JObject>>(r =>
                //{
                   
                //}));

                //BindingList<JObject> products = r.result.records;
                //List<JObject> items = products.ToList();
                //JArray ee = (JArray)JsonConvert.DeserializeObject(items[0]["printParameter"].ToString());
                //JObject data = (JObject)JsonConvert.DeserializeObject(ee[0].ToString());
                //List<Dictionary<string, string>> datas = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(rs);
                //Dictionary<string,string> sysParms = JsonConvert.DeserializeObject<Dictionary<string,string>>(data["printParameter"]);
                //GValues.BlockField_LossRate = 0.0;
                //GValues.BlockField_FenmoLossRate = 0.0;
                //if (data["BlockFieldLossRate"] != null)
                //{
                //    GValues.BlockField_LossRate = double.Parse(data["BlockFieldLossRate"].ToString());
                //}
                //if (data["BlockFieldFenmoLossRate"] != null)
                //{
                //    GValues.BlockField_FenmoLossRate = double.Parse(data["BlockFieldFenmoLossRate"].ToString());
                //}
                setBomMaterialForm.BaigeBlockGetProductCode(new Action<string>(code =>
                {
                    if (code != null)
                    {
                        GValues.productCode = code;
                        GValues.clickButtonText = "插入";
                        //MessageBox.Show("code: " + code);
                        //try
                        //{
                        //    if (GValues.CADMainProductCode != "")
                        //    {
                        //        setBomMaterialForm.SetLayer0XData();
                        //    }
                        //    //setBomMaterialForm.ReadLayer0XData();

                        //    // 检查ReadLayer0XData返回值或添加try-catch

                        //    setBomMaterialForm.ReadLayer0XData();
                        //}
                        //catch (NullReferenceException ex)
                        //{
                        //    MessageBox.Show("读取图层数据失败: " + ex.Message);
                        //    return;
                        //}
                        //catch (System.Exception e)
                        //{
                        //    MessageBox.Show("Bom表格初始化错误", e.Message);
                        //    return;
                        //}


                        Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, setBomMaterialForm);
                        setBomMaterialForm.initBomFormData();
                    }
                    else
                    {
                        MessageBox.Show("系统产品料号没获取到！");
                    }
                }));
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        [CommandMethod("TTE2")]
        public void modifyBomMaterialQty()
        {
            try
            {
                InitDomainConfig();
                getUserInfo();
                //SetObject setObject = new SetObject();
                ModifySelectionTable("product");
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void ModifySelectionTable(String bomType)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            string productCode = "";
            bool isProductBom = false;
            string domainid = "";
            GValues.clickButtonText = "修改";
            PromptSelectionOptions options = new PromptSelectionOptions();
            options.MessageForAdding = "选择表格对象";
            PromptSelectionResult result = ed.GetSelection(options);


            if (result.Status == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    SelectionSet ss = result.Value;
                    foreach (ObjectId id in ss.GetObjectIds())
                    {
                        Entity entity = tr.GetObject(id, OpenMode.ForRead) as Entity;
                        if (entity is Table)
                        {
                            Table table = entity as Table;

                            // 你现在可以使用table对象了
                            // ...
                            if (table.XData != null)
                            {
                                ResultBuffer rb = table.XData; // 获取实体的扩展数据
                                
                                // 遍历ResultBuffer以查看数据
                                foreach (TypedValue tv in rb)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            domainid = tv.Value.ToString();
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            String data = tv.Value.ToString();
                                            if (data.IndexOf("productCode:") != -1)
                                            {
                                                productCode = data.Split(':')[1];
                                            }
                                            if (data.IndexOf("tableType:productBom") != -1)
                                            {
                                                isProductBom = true;
                                            }
                                            break;
                                        // 其他类型的DXF组码...
                                    }
                                }
                            }
                            else
                            {
                                ed.WriteMessage("\n实体没有扩展数据！");
                            }
                        }
                    }
                    tr.Commit();
                }
            }
            if (productCode != "" && isProductBom)
            {
                GValues.productCode = productCode;
                this.ModifyBomCommand("product");

            }
            else
            {
                ed.WriteMessage("\n选择的不是产品BOM表格！");
            }
        }
        private void ModifyBomCommand(String bomType)
        {
            if (setBomMaterialForm == null || setBomMaterialForm.IsDisposed)
            {
                setBomMaterialForm = new SetBomMaterialForm();
            }

            //netApi.getSystemParamater(new Action<ResponResultA<JObject>>(r =>
            //{
               
            //}));

            try
            {
                //BindingList<JObject> products = r.result.records;
                //List<JObject> items = products.ToList();
                //JArray ee = (JArray)JsonConvert.DeserializeObject(items[0]["printParameter"].ToString());
                //JObject data = (JObject)JsonConvert.DeserializeObject(ee[0].ToString());
                //List<Dictionary<string, string>> datas = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(rs);
                //Dictionary<string,string> sysParms = JsonConvert.DeserializeObject<Dictionary<string,string>>(data["printParameter"]);
                //GValues.BlockField_LossRate = 0.0;
                //GValues.BlockField_FenmoLossRate = 0.0;
                //if (data["BlockFieldLossRate"] != null)
                //{
                //    GValues.BlockField_LossRate = double.Parse(data["BlockFieldLossRate"].ToString());
                //}
                //if (data["BlockFieldFenmoLossRate"] != null)
                //{
                //    GValues.BlockField_FenmoLossRate = double.Parse(data["BlockFieldFenmoLossRate"].ToString());
                //}
                Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, setBomMaterialForm);
                setBomMaterialForm.initBomFormData();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("数据转换错误！" + ex.Message);
            }

        }
        //[CommandMethod ("FromHandles")]
        //public void fromHandles()
        //{
        //    SetObject setObject = new SetObject();
        //    setObject.AddToSelectionSetByHandleAndManualSelect();
        //}
        #endregion
        #region 验证命令


        [CommandMethod("GetInBlockToDWGFile")]
        public void GetInBlockToDWGFile()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // 选择块参照
                    PromptEntityOptions opts = new PromptEntityOptions("\n选择块参照: ");
                    opts.SetRejectMessage("\n必须选择块参照");
                    opts.AddAllowedClass(typeof(BlockReference), false);

                    PromptEntityResult res = ed.GetEntity(opts);
                    if (res.Status != PromptStatus.OK) return;

                    BlockReference br = tr.GetObject(res.ObjectId, OpenMode.ForRead) as BlockReference;

                    // 获取块定义
                    BlockTableRecord btr = tr.GetObject(br.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;

                    // 遍历块内实体
                    foreach (ObjectId entId in btr)
                    {
                        Entity ent = tr.GetObject(entId, OpenMode.ForRead) as Entity;

                        // 修正为检测真正的 Table 对象
                        if (ent is Table)
                        {
                            Table table = ent as Table;
                            ResultBuffer xdata = table.XData;

                            if (xdata != null)
                            {
                                TypedValue[] values = xdata.AsArray();
                                ed.WriteMessage("\n找到表格对象（行数：{table.Rows.Count}，列数：{table.Columns.Count}）");
                                // 处理表格的XData...
                            }
                        }
                    }
                    tr.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage("\n错误: {}" + ex.Message);
                }
            }
        }

        [CommandMethod("ExportBlockByHandle")]
    public void ExportBlockByHandle()
    {
        var doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        if (doc == null) return;
        var ed = doc.Editor;
        var db = doc.Database;

        // 1) 读取用户输入的块 HANDLE（十六进制）
        //var pr = ed.GetString("\n请输入块的 HANDLE（十六进制，不含花括号）：");
        //if (pr.Status != PromptStatus.OK) return;
        //string handleStr = pr.StringResult?.Trim();
        //if (string.IsNullOrWhiteSpace(handleStr))
        //{
        //    ed.WriteMessage("\n错误：句柄不能为空。");
        //    return;
        //}

        //// 2) 可选：若用户输入带花括号，去掉花括号
        //if (handleStr.StartsWith("{") && handleStr.EndsWith("}"))
        //    handleStr = handleStr.Substring(1, handleStr.Length - 2);

        // 3) 构造 LISP：把句柄放入变量 u:blockH，然后由 LISP 完成“插入到新图并保存”
        //    注意：这里使用 (command "-INSERT") 避免交互；/n 表示不提示选择点/比例/旋转
        //    路径请按需修改，或改为由 C# 动态生成唯一文件名
        string lspCode = String.Format( @"
            (vl-load-com)
            (setq u:blockH (handent ""{0}""))
            (if (and u:blockH (not (null u:blockH)))
              (progn
                (command ""_.-INSERT"" u:blockH ""0,0"" ""1"" ""1"" ""0"")
                (command ""_.ZOOM"" ""E"")
                (setq u:fn (strcat u:fn ""block_{0}.dwg""))
                (command ""_.SAVEAS"" ""DWG"" u:fn)
                (strcat ""成功：已保存到 "")
              )
              (strcat ""失败：无效的句柄或块定义不存在："" u:blockH)
            )
        ","3AE");

        try
        {
            // 获取 CMDECHO 系统变量的值
            ResultBuffer rb = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("CMDECHO") as ResultBuffer;
            int oldCmdecho = 0;
            if (rb != null)
            {
                foreach (TypedValue tv in rb)
                {
                    if (tv.TypeCode == (int)DxfCode.Int32)
                    {
                        oldCmdecho = (int)tv.Value;
                        break;
                    }
                }
            }

            // 关闭命令行回显
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("CMDECHO", 0);

            // 执行LISP语句
            Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.SendStringToExecute(lspCode + "\n", true, false, false);


            // 恢复命令行回显
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("CMDECHO", oldCmdecho);
            // 启动新任务检查文件
            //Task.Run(() => CheckFileExists(filePath, callback));

            ed.WriteMessage("\nLISP语句执行成功！");
        }
        catch (System.Exception ex)
        {
            ed.WriteMessage("\n执行LISP语句时出错: " + ex.Message);
        }


        //try
        //{
        //    // 4) 发送 LISP 到命令行执行
        //    ed.WriteMessage("\n正在执行 LISP，处理句柄： ..." );
        //    doc.SendStringToExecute(lspCode, true, false, false);
        //}
        //catch (System.Exception ex)
        //{
        //    ed.WriteMessage("\n执行异常：" + ex.Message);
        //}
    }

        #endregion
    }
    public class SimpleProgressBar
    {
        private ProgressBar progressBar;
        private Form form;

        public SimpleProgressBar()
        {
            progressBar = new ProgressBar();
            progressBar.Maximum = 100;
            progressBar.Minimum = 0;
            progressBar.Step = 1;
            progressBar.Value = 0;
        }

        public void Show()
        {
            form = new Form();
            form.Controls.Add(progressBar);
            form.ShowDialog();
        }

        public void Close()
        {
            form.Close();
        }

        public void UpdateProgress(int value)
        {
            if (value >= 0 && value <= 100)
            {
                progressBar.Value = value;
            }
        }
    }

    public class LayerXDataHelper
{
    public ResultBuffer GetLayerXData(string layerName, string appName)
    {
        Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        Database db = doc.Database;
        
        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            try
            {
                // 获取层表
                LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                
                if (lt.Has(layerName))
                {
                    // 获取图层记录
                    LayerTableRecord ltr = tr.GetObject(lt[layerName], OpenMode.ForRead) as LayerTableRecord;
                    
                    // 获取指定应用的XData
                    return ltr.GetXDataForApplication(appName);
                }
                else
                {
                    doc.Editor.WriteMessage("\n图层不存在"+layerName);
                    return null;
                }
            }
            finally
            {
                tr.Commit();
            }
        }
    }
}
}
